6237 Programmering II (Csharp) Agenda/Dictionary
From Teknologisk videncenter
< 6237 Programmering II (Csharp) Agenda
Revision as of 11:22, 7 October 2015 by Orso (talk | contribs) (moved 6237 Programmering II Dictionary to 6237 Programmering II (Csharp) Agenda/Dictionary)
Dictionary
Hvis vi gerne vil tælle hvor mange gange en bestemt webadresse forekommer kan vi anvende dictionary. Et dictionary virker som et array, men i stedet for at indekserer med et tal kan man anvende en string.
IDictionary<string, int> web = new Dictionary<string, int>();
web["www.facebook.com"] = 10;
web["www.dr.dk"] = 20;
web["www.google.com"] = 30;
Hvis vi vil bruge det til at tælle forekomster af en adresse kunne det foregå sådan her.
class Program
{
static IDictionary<string, int> web;
static void AddWebAddress(String address)
{
if (web.ContainsKey(address)) web[address]++;
else web[address] = 1;
}
static void Main(string[] args)
{
web = new Dictionary<string, int>();
AddWebAddress("www.google.com");
AddWebAddress("www.facebook.com");
AddWebAddress("www.google.com");
AddWebAddress("www.dr.com");
AddWebAddress("www.google.com");
AddWebAddress("www.facebook.com");
foreach(string key in web.Keys)
{
System.Console.WriteLine("Adressen {0} optræder {1} gange", key, web[key]);
}
}
}