Reputation: 3445
I want to do something with each object in a C# Dictionary. keyVal.Value
seems a little awkward:
foreach (KeyValuePair<int, Customer> keyVal in customers) {
DoSomething(keyVal.Value);
}
Is there a nicer way to do this that's also fast?
Upvotes: 3
Views: 404
Reputation: 498904
The Dictionary
class has a Values
property that you can directly iterate over:
foreach(var cust in customer.Values)
{
DoSomething(cust);
}
An alternative, if you can use LINQ as Arie van Someren shows in his answer:
customers.Values.Select(cust => DoSomething(cust));
Or:
customers.Select(cust => DoSomething(cust.Value));
Upvotes: 6
Reputation: 457
customers.Select( customer => DoSomething(customer.Value) );
Upvotes: 3
Reputation: 15227
You can always iterate over the keys and get the values. Or, you can iterate over just the values.
foreach(var key in customers.Keys)
{
DoSomething(customers[key]);
}
or
foreach(var customer in customer.Values)
{
DoSomething(customer);
}
Upvotes: 4
Reputation: 25684
If all you care about is the values, and not the keys, then you can use IDictionary.Values
to iterate over.
foreach (Customer val in customers.Values) {
DoSomething(val);
}
Upvotes: 1