Dictionary from list
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class Program { static void Main(string[] args) { //initialize a new generic list of keyvaluepair. List<KeyValuePair<int, string>> birdsList = new List<KeyValuePair<int, string>>(); //create new keyvaluepair. KeyValuePair<int, string> bird1 = new KeyValuePair<int, string>(1, "Canada Goose"); KeyValuePair<int, string> bird2 = new KeyValuePair<int, string>(2, "Cackling Goose"); KeyValuePair<int, string> bird3 = new KeyValuePair<int, string>(3, "Egyptian Goose"); //add keyvaluepair to lsit birdsList.Add(bird1); birdsList.Add(bird2); birdsList.Add(bird3); Console.WriteLine( "generic list elements.........."); foreach (KeyValuePair<int, string> pair in birdsList) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } //create a dictionary from generic list. Dictionary<int, string> birds = birdsList.ToDictionary(x => x.Key, x => x.Value); Console.WriteLine("\ndictionary elements.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 | generic list elements.......... 1 ........ Canada Goose 2 ........ Cackling Goose 3 ........ Egyptian Goose dictionary elements.......... 1 ........ Canada Goose 2 ........ Cackling Goose 3 ........ Egyptian Goose |