LINQ
C#
list
programming
.NET

Checking if a list is empty with LINQ

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Checking whether a list is empty in C# does not require LINQ in most cases. For concrete collections like List and arrays, use Count == 0 or Length == 0. LINQ Any() is best when working with IEnumerable where counting may be expensive or unavailable.

Prefer Direct Properties on Concrete Collections

If the variable type is List<T>, checking Count is simple and fast.

csharp
1using System;
2using System.Collections.Generic;
3
4public class Demo
5{
6    public static void Main()
7    {
8        var numbers = new List<int>();
9        Console.WriteLine(numbers.Count == 0 ? "empty" : "not empty");
10
11        numbers.Add(10);
12        Console.WriteLine(numbers.Count == 0 ? "empty" : "not empty");
13    }
14}

For arrays, use Length == 0.

Use Any() for IEnumerable

IEnumerable<T> may represent streams, generators, or deferred queries where counting all items is unnecessary. Any() short-circuits as soon as first element is found.

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public class CheckEnumerable
6{
7    public static void Main()
8    {
9        IEnumerable<int> source = Enumerable.Range(1, 5).Where(x => x > 3);
10        Console.WriteLine(source.Any() ? "has items" : "empty");
11    }
12}

For remote query providers, Any() also translates efficiently in many cases.

Null-safe Empty Checks

Always handle null references if collection may be optional. Extension patterns keep call sites clean.

csharp
1using System.Collections.Generic;
2using System.Linq;
3
4public static class EnumerableExtensions
5{
6    public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
7    {
8        return source == null || !source.Any();
9    }
10}

This avoids repeated null guards throughout business logic.

Performance and Readability Tradeoffs

For in-memory lists, Count communicates intent clearly and avoids LINQ dependency. For polymorphic abstractions, Any() communicates "existence" and can prevent expensive full enumeration. Pick based on actual type and cost model.

Avoid writing Count() == 0 on an IEnumerable unless you know provider behavior. It can force full traversal and hurt performance on large or streaming inputs.

API Consistency in Shared Libraries

In shared helper libraries, define one emptiness-check convention and apply it consistently. For example, expose IsNullOrEmpty for IEnumerable<T> and use direct Count checks for concrete types inside performance-critical code paths. Consistency reduces review noise and prevents subtle behavioral differences.

csharp
1using System.Collections.Generic;
2using System.Linq;
3
4public static class CollectionRules
5{
6    public static bool HasItems<T>(IEnumerable<T> source)
7    {
8        return source != null && source.Any();
9    }
10}

This helper reads naturally at call sites and captures null handling in one place.

Measuring Before Optimizing

If emptiness checks appear in hot loops, benchmark realistic workloads instead of assuming one method is always faster. The best choice depends on runtime type and provider semantics.

csharp
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4
5var list = new List<int>();
6for (int i = 0; i < 1_000_000; i++) list.Add(i);
7
8var sw = Stopwatch.StartNew();
9for (int i = 0; i < 100_000; i++) _ = list.Count == 0;
10sw.Stop();
11Console.WriteLine($"Count check ms: {sw.ElapsedMilliseconds}");

Performance data plus clear conventions gives teams both speed and readability.

In code reviews, prefer style rules that match data type intent. If the variable is clearly a list, Count reads immediately and avoids extra imports. If it is an abstraction or query, Any() communicates intent better and often avoids full enumeration. Intent-focused checks improve maintainability.

Document these rules in team standards so usage remains consistent across repositories.

Clear conventions lower maintenance cost in large teams.

Common Pitfalls

  • Using LINQ Count() to check emptiness on sequences that require full enumeration.
  • Calling Any() repeatedly on one-time iterators and consuming data unexpectedly.
  • Forgetting null checks when collection references are optional.
  • Mixing List<T> and IEnumerable<T> patterns without considering runtime type.
  • Optimizing prematurely without measuring hot-path behavior.

Summary

  • Use Count == 0 for List<T> and Length == 0 for arrays.
  • Use Any() for IEnumerable<T> when emptiness is the only question.
  • Prefer null-safe helper extensions in shared code.
  • Avoid Count() emptiness checks on deferred or streaming sources.
  • Choose the pattern that matches collection type and performance characteristics.

Course illustration
Course illustration

All Rights Reserved.