I have a quick question. Is there way to easy loop through System.Collections.Generic.Dictionary
via for
statement in C#?
Thanks in advance.
Contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.
Note that the Dictionary<TKey, TValue> has two type parameters, TKey and TValue. TKey is the type of the keys, and TValue is the type of the values (i.e., the data elements associated with the keys). Keys must always be non-null — any attempt to use a null key will result in an ArgumentNullException.
We can use simple for loop to iterate over dictionary key value pairs. We can access the KeyValuePair values by dictionary index using dictionary. ElementAt() function.
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.
You can use foreach:
Dictionary<string,string> dictionary = new Dictionary<string,string>();
// ...
foreach (KeyValuePair<string,string> kv in dictionary)
{
string key = kv.Key;
string value = kv.Value;
}
Not in a reasonable way, no. You could use the Linq extension ElementAt
:
for (int i = 0; i < dictionary.Keys.Count; i++)
{
Console.WriteLine(dictionary.ElementAt(i).Value);
}
...but I really don't see the point. Just use the regular foreach
approach. If you for some reason need to keep track of an index while iterating, you can do that "on the side":
int index = 0;
foreach (var item in dictionary)
{
Console.WriteLine(string.Format("[{0}] - {1}", index, item.Value));
// increment the index
index++;
}
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