views:

630

answers:

3

If I have access only keys from a Dictionary<TKey, TValue> what is better to use:

Dictionary<TKey, TValue>.ForEach(pair => action(pair.Key))

or

Dictionary<TKey, TValue>.Keys.ForEach(key => action(key))

Which method is more 'best-practice' ? Speed in both cases I think seems to be very similar.

+2  A: 

If speed is what you are after then I would suggest that you do this:

foreach (TKey key in yourDictionary.Keys)
    action(key)

This does not require the creation of a delegate for whatever method you are using as action.

Note that this will be a minimal performance benefit since in the case where you create a delegate (as in your two examples) the compiler will hoist the creation of the delegate out of the loop and only create one delegate instance. Still I find foreach cleaner and easier to read than any ForEach extension method.

Andrew Hare
If he has lambdas, he has 'var' to clean up that foreach.
sixlettervariables
+3  A: 

I think this depends entirely on your use case. If you only need to use the key in the predicate, I would use the second version. Otherwise you're adding more information to the lambda than is strictly necessary.

But I don't think there is a hard and fast rule here. Probably just whatever flows off the keyboard more naturally.

Likewise, if you need to use both the key and the value, go with the first.

JaredPar
+2  A: 

I prefer to use

foreach (TKey key in dictionary.Keys)
{
    DoStuff(key);
}

if I only need the keys because it expresses the intention much better than iterating over the key value pairs and it is not slow - accessing a key is O(1).

Daniel Brückner
Actually, I don't think it states any specific performance for simply iterating the keys (although we should typically assume O(N) for a "foreach") - the O(1) only applies when accessing values from a key.
Marc Gravell
I should have added that accessing the Keys property is O(1) - it's usually the fear that accessing this property will create a new array with all keys.
Daniel Brückner