Difference between revisions of "Dictionary Csharp"

From Teknologisk videncenter
Jump to: navigation, search
m (Created page with "=Example= <source=Csharp> using System; using System.Collections.Generic; Dictionary<string, int> ages = new Dictionary<string, int>(); // fill the Dictionary ages.Add("John", ...")
 
m
Line 1: Line 1:
 
=Example=
 
=Example=
<source=Csharp>
+
<source lang=Csharp>
 
using System;
 
using System;
 
using System.Collections.Generic;
 
using System.Collections.Generic;

Revision as of 12:11, 19 January 2017

Example

using System;
using System.Collections.Generic;

Dictionary<string, int> ages = new Dictionary<string, int>();

// fill the Dictionary
ages.Add("John", 51);    // using the Add method
ages.Add("Diana", 50);
ages["James"] = 23;      // using array notation
ages["Francesca"] = 21;

// iterate using a foreach statement
// the iterator generates a KeyValuePair item
Console.WriteLine("The Dictionary contains:");

foreach (KeyValuePair<string, int> element in ages)
{
    string name = element.Key;
    int age = element.Value;
    Console.WriteLine($"Name: {name}, Age: {age}");
}