Does C# have IsNullOrEmpty for List/IEnumerable?

前端 未结 10 440
一生所求
一生所求 2020-12-23 11:04

I know generally empty List is more prefer than NULL. But I am going to return NULL, for mainly two reasons

  1. I have to check and handle null values explicitly,
相关标签:
10条回答
  • 2020-12-23 11:47
    var nullOrEmpty = !( list?.Count > 0 );
    
    0 讨论(0)
  • 2020-12-23 11:53

    for me best isNullOrEmpty method is looked like this

    public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
    {
        return !enumerable?.Any() ?? true;
    }
    
    0 讨论(0)
  • 2020-12-23 11:54

    If you need to be able to retrieve all of the elements in the case of it not being empty, then some of the answers here won't work, because the call to Any() on a non-rewindable enumerable will "forget" an element.

    You could take a different approach and turn nulls into empties:

    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).
    }
    

    Likewise (someEnumeration ?? Enumerable.Empty<MyType>()).ToList() etc. can be used.

    0 讨论(0)
  • 2020-12-23 11:55

    Putting together the previous answers into a simple extension method for C# 6.0+:

        public static bool IsNullOrEmpty<T>(this IEnumerable<T> me) => !me?.Any() ?? true;
    
    0 讨论(0)
提交回复
热议问题