开发者

foreach with key in dictionary

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

foreach(somedictionary<"thiskey开发者_StackOverflow", x>...?

/M


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


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.


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜