119

I have a List where sometimes it is empty or null. I want to be able to check if it contains any List-item and if not then add an object to the List.

 // I have a list, sometimes it doesn't have any data added to it
    var myList = new List<object>(); 
 // Expression is always false
    if (myList == null) 
        Console.WriteLine("List is never null"); 
    if (myList[0] == null) 
        myList.Add("new item"); 
    //Errors encountered:  Index was out of range. Must be non-negative and less than the size of the collection.
    // Inner Exception says "null"
Olorunfemi Davis
  • 1,001
  • 10
  • 23
Jonathan Kittell
  • 7,163
  • 15
  • 50
  • 93
  • 9
    please change your accepted answer to L-Four's answer as it is far better than mine and the question seems to be useful for many so let the better answer be selected. – Amit Joki Jan 09 '18 at 15:20

25 Answers25

166

Try the following code:

 if ( (myList!= null) && (!myList.Any()) )
 {
     // Add new item
     myList.Add("new item"); 
 }

A late EDIT because for these checks I now like to use the following solution. First, add a small reusable extension method called Safe():

public static class IEnumerableExtension
{       
    public static IEnumerable<T> Safe<T>(this IEnumerable<T> source)
    {
        if (source == null)
        {
            yield break;
        }

        foreach (var item in source)
        {
            yield return item;
        }
    }
}

And then, you can do the same like:

 if (!myList.Safe().Any())
 {
      // Add new item
      myList.Add("new item"); 
 }

I personally find this less verbose and easier to read. You can now safely access any collection without the need for a null check.

And another EDIT, which doesn't require an extension method, but uses the ? (Null-conditional) operator (C# 6.0):

if (!(myList?.Any() ?? false))
{
    // Add new item
    myList.Add("new item"); 
}
L-Four
  • 13,345
  • 9
  • 65
  • 109
  • 9
    we can use `myList?.Count() > 0` or `myList?Length > 0` or `myList?.Any()`? – amit jha Apr 06 '18 at 12:27
  • 6
    Null-Conditional usage needs to be fixed to something like `if (!(myList?.Any() ?? false))` to overcome the `Cannot implicitly convert type bool? to bool` error – mishal153 Nov 17 '19 at 10:34
  • 5
    Comparing `if (!list?.Any() ?? false) {}` (3 operators) with `if (list?.Any() != true) {}` (2 operators), I like the latter. – themefield Aug 20 '20 at 22:50
  • if `myList` is `null`, `myList?.Any()` will return `null`, hence `myList?.Any() == false` would not hold. – Insiyah_Hajoori Aug 27 '21 at 06:47
  • BTW, if adding a `Safe` static extension method, might as well add `SafeAny`: `public static bool SafeAny(this IEnumerable source) => source != null && source.Any();`. [aka `HasItems`, which is what I call it.] `if (!list.HasItems())`: short and sweet. – ToolmakerSteve Oct 20 '22 at 18:46
99

For anyone who doesn't have the guarantee that the list will not be null, you can use the null-conditional operator to safely check for null and empty lists in a single conditional statement:

if (list?.Any() != true)
{
    // Handle null or empty list
}
Eliasar
  • 1,067
  • 1
  • 7
  • 18
mech
  • 2,775
  • 5
  • 30
  • 38
  • 1
    `if (list?.Any().GetValueOrDefault())` - can be another approach which remove negated comparison – Basin Nov 03 '18 at 20:48
  • Do you mean `if (list?.Any()?.GetValueOrDefault())`? Yes, that would be another good approach. It's a bit less obvious (to me. at least) at a glance, but it's an equally good solution :) – mech Nov 09 '18 at 06:15
  • yes, I try to avoid negated condition, if possible, every time I see `!variable` or `!=` ;) – Basin Nov 19 '18 at 09:47
  • Might be a good alternativ ? `if (list?.Any() is false)` – Puygrenier Solann Oct 04 '22 at 13:01
  • That is not equivalent, as `null is false` would not evaluate to true--that, for example, allows you to distinguish what is in a `bool?` variable. – mech Oct 06 '22 at 02:30
  • for better performance (in nullable context) use: `if (list?.Count == 0)` – jawa Oct 11 '22 at 12:53
19

Checkout L-Four's answer.

A less-efficient answer:

if(myList.Count == 0){
    // nothing is there. Add here
}

Basically new List<T> will not be null but will have no elements. As is noted in the comments, the above will throw an exception if the list is uninstantiated. But as for the snippet in the question, where it is instantiated, the above will work just fine.

If you need to check for null, then it would be:

if(myList != null && myList.Count == 0){
  // The list is empty. Add something here
}

Even better would be to use !myList.Any() and as is mentioned in the aforementioned L-Four's answer as short circuiting is faster than linear counting of the elements in the list.

Community
  • 1
  • 1
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • 67
    this will throw an exception when the list is null – TechSavvySam Nov 09 '15 at 13:13
  • 5
    not the good answer... use it if you know that the list is instancied – Pierre May 03 '17 at 11:44
  • 1
    Instead of `myList.Count == 0` Use `myList.Any()` which is more common, readable and clear. – Sumit Joshi Jan 08 '18 at 06:15
  • @SumitJoshi It is also more efficient. Count will check each element of the list. – rmlarsen Jan 09 '18 at 14:43
  • @rmlarsen myList.Count does not iterate over the list. List internally maintains a variable to keep its size. It is just like reading a property. It is an O(1) operation [ref](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.count?redirectedfrom=MSDN&view=net-5.0#System_Collections_Generic_List_1_Count) – manjeet lama Jun 27 '21 at 23:47
  • how can it be 19 votes up, it should be minus votes, and this answer should be banned. – Ozmen Nov 08 '22 at 16:32
16

What about using an extension method?

public static bool AnyOrNotNull<T>(this IEnumerable<T> source)
{
  if (source != null && source.Any())
    return true;
  else
    return false;
}
swissben
  • 1,059
  • 8
  • 13
13

An easy way to combine myList == null || myList.Count == 0 would be to use the null coalescing operator ??:

if ((myList?.Count ?? 0) == 0) {
    //My list is null or empty
}
Mattkwish
  • 753
  • 7
  • 16
9
if (myList?.Any() == true) 
{
   ...
}

I find this the most convenient way. '== true' checks the value of the nullable bool implied by '?.Any()

bvh9000
  • 121
  • 1
  • 4
9

I was wondering nobody suggested to create own extension method more readable name for OP's case.

public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
    if (source == null)
    {
        return true;
    }

    return source.Any() == false;
}
Basin
  • 887
  • 1
  • 14
  • 28
  • Use `(this IEnumerable? source)` instead – Zun Apr 26 '21 at 12:49
  • `source.Any() == false` should actually be `!source.Any()`. `== false` only makes sense for `bool?` type, but `Enumerable.Any()` returns `bool` type. – Kim Homann Mar 18 '22 at 09:30
7

Assuming that the list is never null, the following code checks if the list is empty and adds a new element if empty:

if (!myList.Any())
{
    myList.Add("new item");
}

If it is possible that the list is null, a null check must be added before the Any() condition:

if (myList != null && !myList.Any())
{
    myList.Add("new item");
}

In my opinion, using Any() instead of Count == 0 is preferable since it better expresses the intent of checking if the list has any element or is empty. However, considering the performance of each approach, using Any() is generally slower than Count.

Community
  • 1
  • 1
Luca Cremonesi
  • 144
  • 2
  • 3
  • 13
7

The IsNullOrEmpty() extension method is a very elegant and human-readable way of implementing this, so I decided to use it. However, you can achieve the same thing without extension methods, too.

Let's say we have an object named list of type List<T> (e.g. List<string>). If you want to know whether the list has items, you can say:

list?.Count > 0 // List<T> has items

This will return false for an empty list and also if the list itself is a null object, true otherwise.

So the only thing you need to do if you want to check whether the list doesn't have any items is to invert the above expression:

!(list?.Count > 0) // List<T> is null or empty

This will return true for an empty list and also if the list itself is a null object, false otherwise. Exactly what you expect from an IsNullOrEmpty evaluation. Just a little cryptic!

As List<T> implements IEnumerable<T>, you can implement the same thing less specific, but this will possibly make the evaluation slower:

list?.Any() != true // IEnumerable<T> is null or empty
Kim Homann
  • 3,042
  • 1
  • 17
  • 20
3

myList[0] gets the first item in the list. Since the list is empty there is no item to get and you get the IndexOutOfRangeException instead.

As other answers here have shown, in order to check if the list is empty you need to get the number of elements in the list (myList.Count) or use the LINQ method .Any() which will return true if there are any elements in the list.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
3

Your List has no items, that's why access to non-existing 0th item

myList[0] == null

throws Index was out of range exception; when you want to access n-th item check

  if (myList.Count > n)
    DoSomething(myList[n])

in your case

  if (myList.Count > 0) // <- You can safely get 0-th item
    if (myList[0] == null) 
      myList.Add("new item");
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
3

Most answers here focused on how to check if a collection is Empty or Null which was quite straight forward as demonstrated by them.

Like many people here, I was also wondering why does not Microsoft itself provide such a basic feature which is already provided for String type (String.IsNullOrEmpty())? Then I encountered this guideline from Microsoft where it says:

X DO NOT return null values from collection properties or from methods returning collections. Return an empty collection or an empty array instead.

The general rule is that null and empty (0 item) collections or arrays should be treated the same.

So, ideally you should never have a collection which is null if you follow this guideline from Microsoft. And that will help you to remove unnecessary null checking which ultimately will make your code more readable. In this case, someone just need to check : myList.Any() to find out whether there is any element present in the list.

Hope this explanation will help someone who will face same problem in future and wondering why isn't there any such feature to check whether a collection is null or empty.

Md Hasan Ibrahim
  • 1,868
  • 19
  • 27
3

You can check the list is empty or not in multiple ways

1)Checklist is null and then check count is greater than zero like below:-

if (myList != null && myList.Count > 0)
{
    //List has more than one record.
}

2)Checklist null and count greater than zero using LINQ query like below:-

if (myList?.Any() == true)
{
    //List has more than one record.
}
Abhay.Patil
  • 663
  • 1
  • 6
  • 14
3
public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
{
   return !(items?.Any() ?? false);
}

This extension method helps you determine if a list is either null or empty. It can be used as follows:

using System;
using System.Linq;
using System.Collections.Generic;

public static class IEnumerableExtensions
{
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
    {
        return !(items?.Any() ?? false);
    }
}

public class Program
{   
    public static void Main()
    {
        List<string> test1 = null;;
        Console.WriteLine($"List 1 is empty: {test1.IsNullOrEmpty()}");
        //Output: List 1 is empty: True

        var test2 = new System.Collections.Generic.List<string>();
        System.Console.WriteLine($"List 2 is empty: {test2.IsNullOrEmpty()}");
        //Output: List 2 is empty: True

        var test3 = new System.Collections.Generic.List<string>();
        test3.Add("test");
        System.Console.WriteLine($"List 3 is empty: {test3.IsNullOrEmpty()}");
        //Output: List 3 is empty: False
    }
}
Bart Coppens
  • 178
  • 1
  • 7
2

List in c# has a Count property. It can be used like so:

if(myList == null) // Checks if list is null
    // Wasn't initialized
else if(myList.Count == 0) // Checks if the list is empty
    myList.Add("new item");
else // List is valid and has something in it
    // You could access the element in the list if you wanted
Andrew_CS
  • 2,542
  • 1
  • 18
  • 38
2

If you want a single line condition that checks both null and empty, you can use

if (list == null ? true : (!list.Any()))

This will work in older framework versions where the null-conditional operator is not available.

1

Try and use:

if(myList.Any())
{

}

Note: this assmumes myList is not null.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Alexandru Chichinete
  • 1,166
  • 12
  • 23
1

You can use Count property of List in c#

please find below code which checks list empty and null both in a single condition

if(myList == null || myList.Count == 0)
{
    //Do Something 
}
Niraj Trivedi
  • 2,370
  • 22
  • 24
0

We can validate like below with Extension methods. I use them for all of my projects.

  var myList = new List<string>();
  if(!myList.HasValue())
  {
     Console.WriteLine("List has value(s)");              
  }

  if(!myList.HasValue())
  {
     Console.WriteLine("List is either null or empty");           
  }

  if(myList.HasValue())
  {
      if (!myList[0].HasValue()) 
      {
          myList.Add("new item"); 
      }
  }




/// <summary>
/// This Method will return True if List is Not Null and it's items count>0       
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns>Bool</returns>
public static bool HasValue<T>(this IEnumerable<T> items)
{
    if (items != null)
    {
        if (items.Count() > 0)
        {
            return true;
        }
    }
    return false;
}


/// <summary>
/// This Method will return True if List is Not Null and it's items count>0       
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns></returns>
public static bool HasValue<T>(this List<T> items)
{
    if (items != null)
    {
        if (items.Count() > 0)
        {
            return true;
        }
    }
    return false;
}


/// <summary>
///  This method returns true if string not null and not empty  
/// </summary>
/// <param name="ObjectValue"></param>
/// <returns>bool</returns>
public static bool HasValue(this string ObjectValue)
{
    if (ObjectValue != null)
    {
        if ((!string.IsNullOrEmpty(ObjectValue)) && (!string.IsNullOrWhiteSpace(ObjectValue)))
        {
            return true;
        }
    }
    return false;
}
Anandha
  • 41
  • 7
0

We can add an extension to create an empty list

    public static IEnumerable<T> Nullable<T>(this IEnumerable<T> obj)
    {
        if (obj == null)
            return new List<T>();
        else
            return obj;
    }

And use like this

foreach (model in models.Nullable())
{
    ....
}
Damian Haynes
  • 384
  • 3
  • 3
0

I personally create an extension method for the IEnumerable class which I call IsNullOrEmpty(). Because it applies to all implementations of IEnumerable, it works for a List, but also for a String, IReadOnlyList, etc.

My implementation is simply this:

public static class ExtensionMethods
{
    public static bool IsNullOrEmpty(this IEnumerable enumerable)
    {
        if (enumerable is null) return true;

        foreach (var element in enumerable)
        {
            //If we make it here, it means there are elements, and we return false
            return false;
        }

        return true;
    }
}

I can then use the method on a list as follows:

var myList = new List<object>();

if (myList.IsNullOrEmpty())
{
    //Do stuff
}
0

I just wanted to add an answer here since this is the top hit on Google for checking if a List is null or empty. For me .Any is not recognized. If you want to check without creating an extension method you can do it like this which is pretty simple:

//Check that list is NOT null or empty.
if (myList != null && myList.Count > 0)
{
    //then proceed to do something, no issues here.
}

//Check if list is null or empty.
if (myList == null || myList.Count == 0)
{
    //error handling here for null or empty list
}

//checking with if/else-if/else
if (myList == null)
{
    //null handling
}
else if(myList.Count == 0)
{
    //handle zero count
}
else
{
    //no issues here, proceed
}

If there is a possibility the list could be null then you must check for null first - if you try to check the count first and the list happens to be null then it will throw an error. && and || are short-circuit operators, so the second condition is only evaluated if the first is not satisfied.

SendETHToThisAddress
  • 2,756
  • 7
  • 29
  • 54
0

You can add this IEnumerable extension method that returns true if the source sequence either contains any elements and is not null. Otherwise returns false.

public static class IEnumerableExtensions
{
    public static bool IsNotNullNorEmpty<T>(this IEnumerable<T> source)
       => source?.Any() ?? false;
}
Mikolaj
  • 1,231
  • 1
  • 16
  • 34
-1

Because you initialize myList with 'new', the list itself will never be null.

But it can be filled with 'null' values.

In that case .Count > 0 and .Any() will be true. You can check this with the .All(s => s == null)

var myList = new List<object>();
if (myList.Any() || myList.All(s => s == null))
tomerpacific
  • 4,704
  • 13
  • 34
  • 52
Tessa
  • 37
  • 1
-1

This is able to solve your problem `if(list.Length > 0){

}`