How to check if IEnumerable is null or empty?

前端 未结 22 1093
梦如初夏
梦如初夏 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 OrEmpty(this IEnumerable sequence)
    {
        return sequence ?? Enumerable.Empty();
    }
    

    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.

提交回复
热议问题