roslynator
roslynator copied to clipboard
Suggestion: Use Keys/Values enumerators when possible, instead of KeyValuePair enumerator
Collections of type IDictionary<TKey, TValue> implement IEnumerable<KeyValuePair<TKey, TValue>> and also offer direct Values and Keys enumerators.
For these collections, I would like Roslynator to identify this kind of LINQ expression:
collection.First().Key or collection.First().Value
and suggest to refactor it as
collection.Keys.First() or collection.Values.First()
I feel the Keys and Values enumerators are always more efficient than the construction of several KeyValuePair (not usually a native construction of the collection) just for the purpose of accessing their .Key or .Value component
These suggestions should at least be compatible with these LINQ methods: ElementAt, ElementAtOrDefault, First(), FirstOrDefault(), Last(), LastOrDefault(), Single(), SingleOrDefault().
To go further, Min, Max, Sum, Average, Count with selectors, and overloads of the preceding methods taking a predicate, could be also be compatible if it is identified that only the adequate .Key or .Value component is used on the lambda-expression argument KeyValuePair