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>();
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);
}