2
Reply

How to use Dictionary class in Systems.Collections.Generic?

Yogesh Jadhav

Yogesh Jadhav

11y
1.4k
0
Reply

    // Create a new dictionary of strings, with string keys. // Dictionary dictOpenWith = new Dictionary(); // Add some elements to the dictionary. There are no // duplicate keys, but some of the values are duplicates. dictOpenWith.Add("txt", "notepad.exe"); dictOpenWith.Add("bmp", "paint.exe"); dictOpenWith.Add("dib", "paint.exe"); dictOpenWith.Add("rtf", "wordpad.exe");

    Create a Dictionary object and populate it and enumerate it to display key value pairs.

    For example, to create a Dictionary object that has integer as key and string as value, we can create dictionary object in the following way:

    Dictionary dictNames =new Dictionary();

    dictNames.Add(1,”Raj”);

    dictNames.Add(3,”Ravi”);

    dictNames.Add(5,”Kevin”);


    In order to retrieve above value enumerate it i.e use foreach loop and use KeyValuePair object as the elements are retrieved as KeyValuePair objects


    foreach(KeyValuePair kvpName in dictNames)

    Console.WriteLine(kvpName.Key+” “+kvpName.Value);