Lasse Edsvik
Lasse Edsvik

Reputation: 9298

foreach with key in dictionary

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

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

/M

Upvotes: 3

Views: 8437

Answers (4)

DevDave
DevDave

Reputation: 6898

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

Upvotes: 3

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

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.

Upvotes: 4

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

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

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062745

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

Upvotes: 5

Related Questions