Check if list is empty in C# [closed]

I have a generic list object. I need to check if the list is empty.

How do I check if a List<T> is empty in C#?


Solution 1:

You can use Enumerable.Any:

bool isEmpty = !list.Any();
if(isEmpty)
{
    // ...
}  

If the list could be null you could use:

bool isNullOrEmpty = list?.Any() != true;

Solution 2:

If the list implementation you're using is IEnumerable<T> and Linq is an option, you can use Any:

if (!list.Any()) {

}

Otherwise you generally have a Length or Count property on arrays and collection types respectively.