How to check if IEnumerable is null or empty?

前端 未结 22 1024
梦如初夏
梦如初夏 2020-11-27 12:33

I love string.IsNullOrEmpty method. I\'d love to have something that would allow the same functionality for IEnumerable. Is there such? Maybe some collection he

相关标签:
22条回答
  • 2020-11-27 13:16
     public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
        {
            return source != null && source.Any();
        }
    

    my own extension method to check Not null and Any

    0 讨论(0)
  • 2020-11-27 13:17

    Jon Skeet's anwser (https://stackoverflow.com/a/28904021/8207463) has a good approach using Extension Method - Any() for NULL and EMPTY. BUT he´s validating the questions´owner in case for NOT NULL. So carefully change Jon´s approach to validate AS NULL to:

    If (yourList?.Any() != true) 
    {
         ..your code...
    }
    

    DO NOT use ( will not validate AS NULL):

    If (yourList?.Any() == false) 
    {
         ..your code...
    }
    

    You can also in case validating AS NOT NULL ( NOT tested just as example but without compiler error) do something like using predicate :

    If (yourList?.Any(p => p.anyItem == null) == true) 
    {
         ..your code...
    }
    

    https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,8788153112b7ffd0

    For which .NET version you can use it please check:

    https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=netframework-4.8#moniker-applies-to

    0 讨论(0)
  • 2020-11-27 13:19
    if (collection?.Any() == true){
        // if collection contains more than one item
    }
    if (collection?.Any() != true){
        // if collection is null
        // if collection does not contain any item
    }
    
    0 讨论(0)
  • 2020-11-27 13:22

    Another way would be to get the Enumerator and call the MoveNext() method to see if there are any items:

    if (mylist != null && mylist.GetEnumerator().MoveNext())
    {
        // The list is not null or empty
    }
    

    This works for IEnumerable as well as IEnumerable<T>.

    0 讨论(0)
  • 2020-11-27 13:24

    The other best solution as below to check empty or not ?

    for(var item in listEnumerable)
    {
     var count=item.Length;
      if(count>0)
      {
             // not empty or null
       }
      else
      {
           // empty
      }
    }
    
    0 讨论(0)
  • 2020-11-27 13:27
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) {
        return enumerable == null || !enumerable.Any();
    }
    
    0 讨论(0)
提交回复
热议问题