How to check if IEnumerable is null or empty?

前端 未结 22 1023
梦如初夏
梦如初夏 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:28

    Without custom helpers I recommend either ?.Any() ?? false or ?.Any() == true which are relatively concise and only need to specify the sequence once.


    When I want to treat a missing collection like an empty one, I use the following extension method:

    public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> sequence)
    {
        return sequence ?? Enumerable.Empty<T>();
    }
    

    This function can be combined with all LINQ methods and foreach, not just .Any(), which is why I prefer it over the more specialized helper functions people are proposing here.

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

    The way I do it, taking advantage of some modern C# features:

    Option 1)

    public static class Utils {
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
            return !(list?.Any() ?? false);
        }
    }
    

    Option 2)

    public static class Utils {
        public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
            return !(list?.Any()).GetValueOrDefault();
        }
    }
    

    And by the way, never use Count == 0 or Count() == 0 just to check if a collection is empty. Always use Linq's .Any()

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

    I used simple if to check for it

    check out my solution

    foreach (Pet pet in v.Pets)
    {
        if (pet == null)
        {
            Console.WriteLine(" No pet");// enumerator is empty
            break;
        }
        Console.WriteLine("  {0}", pet.Name);
    }
    
    0 讨论(0)
  • 2020-11-27 13:30

    I had the same problem and I solve it like :

        public bool HasMember(IEnumerable<TEntity> Dataset)
        {
            return Dataset != null && Dataset.Any(c=>c!=null);
        }
    

    "c=>c!=null" will ignore all the null entities.

    0 讨论(0)
提交回复
热议问题