Hi folks,
I have a quick question. Is there way to easy loop through System.Collections.Generic.Dictionary
via for
statement in C#?
Thanks in advance.
Hi folks,
I have a quick question. Is there way to easy loop through System.Collections.Generic.Dictionary
via for
statement in C#?
Thanks in advance.
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;
}
No, for
is mostly for collections with indices.
You can foreach
over it easily, however.
You can loop over the keys
for(int i = 0; i < myDictionary.Keys.Length; ++i)
myDictionary.Keys[i] ...
or the values
for(int i = 0; i < myDictionary.Values.Length; ++i)
myDictionary.Values[i] ...
Or both as Philippe shows
If you are using Net 3.5 or later then you can use LINQ and a predecate to locate a specific Value or Values. Dictionaries do not necessarily store their KeyValue pairs in order (either by entry order nor Key order).
There are several ways. Looping through the keys:
foreach(var key in myDictionary.Keys)
looping through values:
foreach(var value in myDic.Values)
looping through pairs:
foreach(KeyValuePair<K, V> p in myDic)
{
var key = p.Key;
var value = p.Value
}
Philippe's got it for foreach
, though I usually simplify it to:
foreach (var pair in dictionary)
{
var key = pair.Key;
var value = pair.Value;
}
There's no way to loop through this collection of key-value pairs using a for
loop because they aren't stored in order. You can loop through the keys or the values as collections though.
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++;
}
It can ofc be done, but it is a bit silly IMO
Dictionary<string,string> dictionary = new Dictionary<string, string>();
Dictionary<string, string>.Enumerator enumerator = dictionary.GetEnumerator();
for (int i = 0; i < attributeValues.Count;i++ )
{
KeyValuePair<string, string> current = enumerator.Current;
//do something usefull
enumerator.MoveNext();
}
the only thing gained by this is a (fairly useless) index, and if that is the actual goal, you are better served by something like this:
int currentIndex = 0;
foreach (KeyValuePair<string, string> keyValuePair in dictionary)
{
//do something usefull
currentIndex++;
}