3

How do I loop a dictionarys values that has a certain key?

foreach(somedictionary<"thiskey", x>...?

/M

ChrisF
  • 134,786
  • 31
  • 255
  • 325
Lasse Edsvik
  • 9,070
  • 16
  • 73
  • 109
  • 2
    A *dictionary* only **has** one value per key, so there is no need to foreach... – Marc Gravell Oct 19 '10 at 11:30
  • You may take a look at this answer [dictionary values in a foreach loop](http://stackoverflow.com/questions/1070766/editing-dictionary-values-in-a-foreach-loop/1070795#1070795) in case you need to iterate over keys. – surfmuggle May 23 '13 at 18:45

4 Answers4

5

A dictionary only has one value per key, so there is no need to foreach... you might just check whether it is there (ContainsKey or TryGetValue):

SomeType value;
if(somedictionary.TryGetValue("thisKey", out value)) {
    Console.WriteLine(value);
}

If SomeType is actually a list, then you could of course do:

List<SomeOtherType> list;
if(somedictionary.TryGetValue("thisKey", out list)) {
    foreach(value in list) {
        Console.WriteLine(value);
    }
}

A lookup (ILookup<TKey,TValue>) has multiple values per key, and is just:

foreach(var value in somedictionary["thisKey"]) {
    Console.WriteLine(value);
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
4

There is at most one value for a given key, so foreach serves no purpose. Perhaps you are thinking of some kind of multimap concept. I don't know if such a thing exists in the .Net class library.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
3

This extension method may be helpful for iterating through Dictionaries:

public static void ForEach<TKey, TValue>(this Dictionary<TKey, TValue> source, Action<KeyValuePair<TKey, TValue>> action) {
   foreach (KeyValuePair<TKey, TValue> item in source)
      action(item);
}
DevDave
  • 6,700
  • 12
  • 65
  • 99
2

Say you have a dictionary declared like this: var d = new Dictionary<string, List<string>>();. You can loop through the values of a list for a given key like this:

foreach(var s in d["yourkey"])
    //Do something
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222