Old Man
Old Man

Reputation: 3445

Loop over Items in a c# Dictionary

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

Answers (5)

Oded
Oded

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

Arie van Someren
Arie van Someren

Reputation: 457

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

Upvotes: 3

viggity
viggity

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

Kyle Trauberman
Kyle Trauberman

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

SLaks
SLaks

Reputation: 887195

foreach (Customer c in customers.Values)

Upvotes: 5

Related Questions