Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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).

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top