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>();
The SortedList<int, string> will store keys of int type and values of string type. The Add() method is used to add a single key-value pair in a SortedList . Keys cannot be null or duplicate.
The SortedList class represents a collection of key-and-value pairs that are sorted by the keys and are accessible by key and by index. A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index.
A SortedList does not allow duplicate keys. Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting. Elements in this collection can be accessed using an integer index.
In C#, SortedList is a collection of key/value pairs which are sorted according to keys. By default, this collection sort the key/value pairs in ascending order. It is of both generic and non-generic type of collection. The generic SortedList is defined in System.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With