Does C # IsNullOrEmpty for List / IEnumerable?

I know that usually an empty list is preferable to NULL. But I'm going to return NULL, mainly for two reasons.

  • I have to explicitly check and handle null values, avoiding errors and attacks.
  • Easy to perform operation ?? after receiving the return value.

For strings, we have IsNullOrEmpty. Is there anything from C # itself that does the same for List or IEnumerable?

+64
c # ienumerable isnullorempty
Dec 20 2018-11-21T00:
source share
10 answers

nothing is baked into the framework, but it is a fairly simple extension method.

Look here

 /// <summary> /// Determines whether the collection is null or contains no elements. /// </summary> /// <typeparam name="T">The IEnumerable type.</typeparam> /// <param name="enumerable">The enumerable, which may be null or empty.</param> /// <returns> /// <c>true</c> if the IEnumerable is null or empty; otherwise, <c>false</c>. /// </returns> public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) { if (enumerable == null) { return true; } /* If this is a list, use the Count property for efficiency. * The Count property is O(1) while IEnumerable.Count() is O(N). */ var collection = enumerable as ICollection<T>; if (collection != null) { return collection.Count < 1; } return !enumerable.Any(); } 

Daniel Vaughan takes the extra step of bringing to ICollection (where possible) for performance reasons. Something that I would not have thought to do.

+67
Dec 20 '11 at 21:45
source share

Late update : starting with C # 6.0, the zero propagation operator can be used to summarize as follows:

 if ( list?.Count > 0 ) // For List<T> if ( array?.Length > 0 ) // For Array<T> 

or, as a more understandable and more general alternative for IEnumerable<T> :

 if ( enumerable?.Any() ?? false ) 



Note 1: all the top options actually reflect IsNotNullOrEmpty , unlike the OP question ( quote ):

Due to the priority of the IsNullOrEmpty operator IsNullOrEmpty equivalents look less attractive:
if (!(list?.Count > 0))

Note 2: ?? false ?? false necessary for the following reason (resume / quote from this post ):

The operator ?. will return null if the child is null . But [...] if we try to get a non- Nullable member, for example, the Any() method, which returns the bool [...] compiler to "wrap" the return value in Nullable<> . For example, Object?.Any() will give us a bool? (i.e. Nullable<bool> ), not bool . [...] Since it cannot be implicitly cast to bool , this expression cannot be used in if

Note 3: as a bonus, the expression is also β€œthread-oriented” (quote from the answer to this question ):

In a multi-threaded context, if [enumerable] is accessible from another thread (either because it is a field that is accessible or because it is closed in a lambda that is exposed to another thread), then the value may differ each time it is calculated [t. e .prior null-check]

+40
Jan 31 '17 at 14:05
source share

There is nothing built in.

This is a simple extension method:

 public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) { if(enumerable == null) return true; return !enumerable.Any(); } 
+24
Dec 20 2018-11-21T00:
source share
 var nullOrEmpty = list == null || !list.Any(); 
+9
Dec 20 2018-11-21T00:
source share

Combining previous answers into a simple extension method for C # 6.0 +:

  public static bool IsNullOrEmpty<T>(this IEnumerable<T> me) => !me?.Any() ?? true; 
+3
Mar 10 '17 at 23:37
source share

If you need to get all the elements in case it is not empty, then some of the answers here will not work, because calling Any() on a non-rewind enumerated element will "forget" it.

You can use a different approach and turn nulls into empty containers:

 bool didSomething = false; foreach(var element in someEnumeration ?? Enumerable.Empty<MyType>()) { //some sensible thing to do on element... didSomething = true; } if(!didSomething) { //handle the fact that it was null or empty (without caring which). } 

You can also use (someEnumeration ?? Enumerable.Empty<MyType>()).ToList() , etc.

+1
Dec 20 2018-11-21T00:
source share

Like everyone else, nothing is built into the infrastructure, but if you use Castle, then Castle.Core.Internal has this.

 using Castle.Core.Internal; namespace PhoneNumbers { public class PhoneNumberService : IPhoneNumberService { public void ConsolidateNumbers(Account accountRequest) { if (accountRequest.Addresses.IsNullOrEmpty()) // Addresses is List<T> { return; } ... 
+1
Mar 19 '14 at 11:12
source share

I modified the sentence from Matthew Wien to avoid the "possible multiple enumeration of IEnumerable" problems. (see also comment from John Hannah)

 public static bool IsNullOrEmpty(this IEnumerable items) => items == null || (items as ICollection)?.Count == 0 || !items.GetEnumerator().MoveNext(); 

... and unit test:

 [Test] public void TestEnumerableEx() { List<int> list = null; Assert.IsTrue(list.IsNullOrEmpty()); list = new List<int>(); Assert.IsTrue(list.IsNullOrEmpty()); list.AddRange(new []{1, 2, 3}); Assert.IsFalse(list.IsNullOrEmpty()); var enumerator = list.GetEnumerator(); for(var i = 1; i <= list.Count; i++) { Assert.IsFalse(list.IsNullOrEmpty()); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(i, enumerator.Current); } Assert.IsFalse(list.IsNullOrEmpty()); Assert.IsFalse(enumerator.MoveNext()); } 
0
Jul 18 '16 at 10:57
source share

for me the best method isNullOrEmpty looks like this

 public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) { return !enumerable?.Any() ?? true; } 
0
Feb 06 '19 at 8:59
source share
 var nullOrEmpty = !( list?.Count > 0 ); 
-one
Sep 27 '16 at 11:43
source share



All Articles