我希望能够在C#字典中对每个对象进行操作。使用keyVal.Value
似乎有些棘手:
foreach (KeyValuePair<int, Customer> keyVal in customers) {
DoSomething(keyVal.Value);
}
有没有更好的方法,既能更美观又能快速完成?
我希望能够在C#字典中对每个对象进行操作。使用keyVal.Value
似乎有些棘手:
foreach (KeyValuePair<int, Customer> keyVal in customers) {
DoSomething(keyVal.Value);
}
有没有更好的方法,既能更美观又能快速完成?
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));
.Value
。在这个上下文中,cust
的类型是KeyValuePair<string, Customer>
。 - Kyle Traubermanforeach (Customer c in customers.Values)
您可以始终遍历键并获取值。或者,您可以仅遍历值。
foreach(var key in customers.Keys)
{
DoSomething(customers[key]);
}
或者
foreach(var customer in customer.Values)
{
DoSomething(customer);
}
customers.Select( customer => DoSomething(customer.Value) );
DoSomething
返回一个值。 - Kyle TraubermanIDictionary.Values
进行迭代。foreach (Customer val in customers.Values) {
DoSomething(val);
}
customers.Values
。 - Gabe