How to Check if a List is Empty
In C#, you can check if a List is empty using the Count property or the LINQ Any() method.
Using Count == 0 is direct and efficient for lists.
Any() is often more readable and can be faster for other types of collections that don't have a quick Count implementation, as it stops checking after finding the first item.
C# Example Code
using System;
using System.Collections.Generic;
using System.Linq;
public class ListCheck
{
public static void Main(string[] args)
{
var emptyList = new List<string>();
var fullList = new List<string> { "one", "two" };
// Using Count property (most common for List<T>)
if (emptyList.Count == 0)
{
Console.WriteLine("List is empty (checked with Count).");
}
// Using LINQ Any()
if (!fullList.Any())
{
Console.WriteLine("This won't be printed.");
}
else
{
Console.WriteLine("List has elements (checked with Any()).");
}
}
}