Tag Archives: LINQ

Keeping it simple – sometimes you don’t need to call .Any()

Something I’ve seen quite a lot of in the codebase I’m working on…

If a collection is empty, the count is 0 and the enumerator is valid but won’t return any items – so there is no need to call .Any() before summing or enumerating.

Count() example

articleTagListForTagGroup
    .Where(tag => tag.ChildTags.Any())
    .Sum(tag => tag.ChildTags.Count());

Because .Count() returns 0 if there aren’t any, this can be reduced to:

articleTagListForTagGroup
     .Sum(tag => tag.ChildTags.Count());

Enumerator / foreach example

if (tag.ChildTags.Any()) {
    foreach (var childTag in tag.ChildTags) {
        // Display

If there aren’t any ChildTags then the foreach has nothing to iterate over – but it won’t throw an error, it just jumps over the code block. It can be simplified to:

foreach (var childTag in tag.ChildTags) {
    // Display