在c#字典中循环遍历项

3

我希望能够在C#字典中对每个对象进行操作。使用keyVal.Value似乎有些棘手:

foreach (KeyValuePair<int, Customer> keyVal in customers) {
    DoSomething(keyVal.Value);
}

有没有更好的方法,既能更美观又能快速完成?


2
你只需要值吗?如果是这样,请使用 customers.Values - Gabe
5个回答

6

Dictionary类有一个Values属性,您可以直接迭代:

foreach(var cust in customer.Values)
{
  DoSomething(cust);
}

如果您可以像Arie van Someren在他的回答中展示的那样使用LINQ,则可以选择另一种方法:

customers.Values.Select(cust => DoSomething(cust));

或者:

customers.Select(cust => DoSomething(cust.Value));

在你的linq中需要使用.Value。在这个上下文中,cust的类型是KeyValuePair<string, Customer> - Kyle Trauberman
@KyleTrauberman - 感谢您的更正。我也添加了另一种替代方案。 - Oded

5
foreach (Customer c in customers.Values)

4

您可以始终遍历键并获取值。或者,您可以仅遍历值。

foreach(var key in customers.Keys)
{
    DoSomething(customers[key]);
}

或者

foreach(var customer in customer.Values)
{
    DoSomething(customer);
}

3
customers.Select( customer => DoSomething(customer.Value) );

假设 DoSomething 返回一个值。 - Kyle Trauberman

1
如果您只关心值而不关心键,则可以使用 IDictionary.Values 进行迭代。
foreach (Customer val in customers.Values) {
    DoSomething(val);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接