Reputation: 7493
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"
Upvotes: 124
Views: 548961
Reputation: 4377
While the accepted answer is a good solution, a way to do it "in one go" is like the following
if (list?.Count() > 0)
So, if list is null or has no items, the if statement will fail
Upvotes: 2
Reputation: 3229
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
Upvotes: 7
Reputation: 208
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
}
}
Upvotes: 4
Reputation: 13531
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");
}
Upvotes: 171
Reputation: 743
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.
}
Upvotes: 3
Reputation: 1869
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;
}
Upvotes: 0
Reputation: 3704
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.
Upvotes: 0
Reputation: 47
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
}
Upvotes: 0
Reputation: 1898
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.
Upvotes: 3
Reputation: 770
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
}
Upvotes: 14
Reputation: 544
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())
{
....
}
Upvotes: 0
Reputation: 37
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))
Upvotes: -1
Reputation: 1017
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;
}
Upvotes: 9
Reputation: 131
if (myList?.Any() == true)
{
...
}
I find this the most convenient way. '== true' checks the value of the nullable bool implied by '?.Any()
Upvotes: 10
Reputation: 2870
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
}
Upvotes: 1
Reputation: 59232
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.
Upvotes: 19
Reputation: 49
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.
Upvotes: 2
Reputation: 2913
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
}
Upvotes: 111
Reputation: 41
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;
}
Upvotes: 0
Reputation: 1183
Try and use:
if(myList.Any())
{
}
Note: this assmumes myList is not null.
Upvotes: 1
Reputation: 1077
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;
}
Upvotes: 17
Reputation: 146
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
.
Upvotes: 7
Reputation: 32576
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.
Upvotes: 3
Reputation: 186668
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");
Upvotes: 3
Reputation: 2562
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
Upvotes: 2