C# – better to use: Dictionary<>.ForEach(pair =>) or Dictionary<>.Keys.ForEach(key =>)

.netc++extension-methodsgenerics

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.

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