YetAnohterOne
YetAnohterOne
CC#
Created by YetAnohterOne on 2/13/2025 in #help
Can I / should I enumerate over an IGrouping more than once?
var groupings = myList.GroupBy(listElement => listElement.Key);
foreach(var groupoing in groupings)
{
foreach(var elt in grouping)
DoSomething(elt);
foreach(var elt2 in grouping)
DoSomethingElse(elt2);
}
var groupings = myList.GroupBy(listElement => listElement.Key);
foreach(var groupoing in groupings)
{
foreach(var elt in grouping)
DoSomething(elt);
foreach(var elt2 in grouping)
DoSomethingElse(elt2);
}
Is this code correct / safe? Is it safe to iterate an IGrouping more than once? Or should I rather do:
var groupings = myList.GroupBy(listElement => listElement.Key);
foreach(var grouping in groupings)
{
var groupingList = grouping.ToList();
foreach(var elt in groupingList)
DoSomething(elt);
foreach(var elt2 in groupoingList)
DoSomethingElse(elt2);
}
var groupings = myList.GroupBy(listElement => listElement.Key);
foreach(var grouping in groupings)
{
var groupingList = grouping.ToList();
foreach(var elt in groupingList)
DoSomething(elt);
foreach(var elt2 in groupoingList)
DoSomethingElse(elt2);
}
16 replies
CC#
Created by YetAnohterOne on 2/6/2025 in #help
CA1860: Avoid using 'Enumerable.Any()' extension method
https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1860 Does this rule make any sense? The rule description says: "To determine whether a collection type has any elements, it's more efficient and clearer to use the Length, Count, or IsEmpty (if possible) properties than to call the Enumerable.Any method. Any(), which is an extension method, uses language integrated query (LINQ). It's more efficient to rely on the collection's own properties, and it also clarifies intent." Does using Count truly clarify intent? I was always using .Any() because I thought it is far clearer - Count != 0 just asks to be extracted into a method, the intent is not to check the number of elements, but whether the collection has Any elements. I really miss an Empty property or method, but the next best thing is !collection.Any() or, even better, an extension method: public static Empty<T>(this IEnumerable<T> enumerable) => !enumerable.Any(). But VisualStudio yells at me now and suggests me to use Count == 0 or Count != 0 instead. Also note that Count bears the risk of accidentally messing up != with == or vice-versa. The rule description mentions the IsEmpty property, but note that the two most common cases (List and Array) have no such property. Finally the rule mentions performance, but isn't this a typical case of premature optimization? Unless I'm in a tight loop, the 10ms saved by avoid .Any() won't matter, and .Any() does seem clearer, which is what matters. Am I missing something? Are there really any outstanding reasons to avoid Any()? Because I feel ready to rebel and just suppress this suggestion.
59 replies