How to loop through a SortedList, getting both the key and the value

Wayneio picture Wayneio · Dec 23, 2012 · Viewed 38.3k times · Source

The following code loops through a list and gets the values, but how would I write a similar statement that gets both the keys and the values

foreach (string value in list.Values)
{
    Console.WriteLine(value);
}

e.g something like this

    foreach (string value in list.Values)
{
    Console.WriteLine(value);
        Console.WriteLine(list.key);
}

code for the list is:

SortedList<string, string> list = new SortedList<string, string>();

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Dec 23, 2012
foreach (KeyValuePair<string, string> kvp in list)
{
    Console.WriteLine(kvp.Value);
    Console.WriteLine(kvp.Key);
}

From msdn:

GetEnumerator returns an enumerator of type KeyValuePair<TKey, TValue> that iterates through the SortedList<TKey, TValue>.

As Jon stated, you can use var keyword instead of writing type name of iteration variable (type will be inferred from usage):

foreach (var kvp in list)
{
    Console.WriteLine(kvp.Value);
    Console.WriteLine(kvp.Key);
}