foreach用词典中的键

Las*_*vik 2 c#

如何循环具有某个键的dictionarys值?

foreach(somedictionary<"thiskey", x>...?
Run Code Online (Sandbox Code Playgroud)

/ M

Mar*_*ell 5

一个字典具有每一个关键值,所以没有必要的foreach ...你可能只是检查是否存在(ContainsKeyTryGetValue):

SomeType value;
if(somedictionary.TryGetValue("thisKey", out value)) {
    Console.WriteLine(value);
}
Run Code Online (Sandbox Code Playgroud)

如果SomeType实际上是一个列表,那么你当然可以这样做:

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

一个查找(ILookup<TKey,TValue>)的每个键多个值,而仅仅是:

foreach(var value in somedictionary["thisKey"]) {
    Console.WriteLine(value);
}
Run Code Online (Sandbox Code Playgroud)