Check If IEnumerable<> or List<> Type is Empty / Null

There are three ways to check whether IEnumerable<> or List<> type is empty / null or not.

== NULL

List<string> EquipmentList = new List<string>();
 
if (EquipmentList != null)
{
    // True, the list is not empty
}
else
{
    // False, the list is empty
}

.Any()

List<string> EquipmentList = new List<string>();
 
if (EquipmentList.Any())
{
    // True, the list is not empty
}
else
{
    // False, the list is empty
}

.Count()

List<string> EquipmentList = new List<string>();
 
if (EquipmentList.Count() != 0)
{
    // True, the list is not empty
}
else
{
    // False, the list is empty
}

In any case, you always want to combine “== null” and, either “.Any()” or “.Count()”, with OR (“||”) operator.

In addition, you want to put “== null” before the other condition. The reason for this is, “if” condition goes from left to right. So, if the list object is null, it will not go to the second check, which will result in “Object reference not set to an instance of an object” exception if the list object is null.

List<string> EquipmentList = new List<string>();
 
if (EquipmentList != null || EquipmentList.Count() != 0)
{
    // True, the list is not empty
}
else
{
    // False, the list is empty
}