Saturday, December 1, 2012

Get Dictionary key Value pairs using List in C#

A Dictionary class represents a dictionary in C# that is used to represent a collection of keys and values pair of data.

 Dictionary<TKey, TValue>

The type of the keys in the dictionary.

The type of the values in the dictionary.

List is a generic type which can hold a collection of objects.

We can write a method to store collection of key values pairs in a dictionary and store collection of dictionaries in a List and then get the key, value pairs of those dictionaries by iterating through the list items.

private void PrintDictionarykeyvalue()
        Dictionary<int, string> dict = new Dictionary<int, string>();
        dict.Add(1, "a");
        dict.Add(2, "b");
        dict.Add(3, "c");

        List<Dictionary<int, string>> lst = new List<Dictionary<int, string>>();

        StringBuilder SB = new StringBuilder();
        foreach (Dictionary<int,string> Dictitem in lst)
            foreach (KeyValuePair<int,string> KeyValitem in Dictitem)
                SB.Append("Key: " + KeyValitem.Key + " , " + " Value: " + KeyValitem.Value);



Out Put:
Key: 1 , Value: a
Key: 2 , Value: b
Key: 3 , Value: c

No comments:
Write comments
Recommended Posts × +