循环遍历ac#Dictionary中的项目

Old*_*Man 3 c#

我想对C#字典中的每个对象做一些事情.keyVal.Value看起来有点尴尬:

foreach (KeyValuePair<int, Customer> keyVal in customers) {
    DoSomething(keyVal.Value);
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来做到这一点也快?

Ode*_*ded 6

Dictionary班有一个Values你可以直接遍历属性:

foreach(var cust in customer.Values)
{
  DoSomething(cust);
}
Run Code Online (Sandbox Code Playgroud)

另一种选择,如果您可以使用LINQ作为Arie van Someren在他的回答中显示:

customers.Values.Select(cust => DoSomething(cust));
Run Code Online (Sandbox Code Playgroud)

要么:

customers.Select(cust => DoSomething(cust.Value));
Run Code Online (Sandbox Code Playgroud)


SLa*_*aks 5

foreach (Customer c in customers.Values)
Run Code Online (Sandbox Code Playgroud)