Difference between revisions of "6237 Programmering II (Csharp) Agenda/Dictionary"
From Teknologisk videncenter
m (added Category:C sharp using HotCat) |
|||
(One intermediate revision by one other user not shown) | |||
Line 6: | Line 6: | ||
<source lang=csharp> | <source lang=csharp> | ||
− | + | Dictionary<string, int> web = new Dictionary<string, int>(); | |
web["www.facebook.com"] = 10; | web["www.facebook.com"] = 10; | ||
web["www.dr.dk"] = 20; | web["www.dr.dk"] = 20; | ||
Line 43: | Line 43: | ||
[[Category:6237 Programmering II]] | [[Category:6237 Programmering II]] | ||
+ | [[Category:C sharp]] |
Latest revision as of 06:42, 31 October 2016
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.
Dictionary<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]);
}
}
}