Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for empty or null List<string>

Tags:

c#

list

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" 
like image 825
Jonathan Kittell Avatar asked Jun 24 '14 15:06

Jonathan Kittell


People also ask

How do you check if a list is null or empty?

isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.

Is an empty list a null list?

An empty collection isn't the same as null . An empty collection is actually a collection, but there aren't any elements in it yet. null means no collection exists at all.

How check if list is empty C#?

Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.


2 Answers

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");  } 
like image 146
L-Four Avatar answered Oct 16 '22 14:10

L-Four


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 } 
like image 36
mech Avatar answered Oct 16 '22 14:10

mech