How to check if IEnumerable is null or empty?

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

    Starting with C#6 you can use null propagation: myList?.Any() == true

    If you still find this too cloggy or prefer a good ol' extension method, I would recommend Matt Greer and Marc Gravell's answers, yet with a bit of extended functionality for completeness.

    Their answers provide the same basic functionality, but each from another perspective. Matt's answer uses the string.IsNullOrEmpty-mentality, whereas Marc's answer takes Linq's .Any() road to get the job done.

    I am personally inclined to use the .Any() road, but would like to add the condition checking functionality from the method's other overload:

        public static bool AnyNotNull(this IEnumerable source, Func predicate = null)
        {
            if (source == null) return false;
            return predicate == null
                ? source.Any()
                : source.Any(predicate);
        }
    

    So you can still do things like : myList.AnyNotNull(item=>item.AnswerToLife == 42); as you could with the regular .Any() but with the added null check

    Note that with the C#6 way: myList?.Any() returns a bool? rather than a bool, which is the actual effect of propagating null

提交回复
热议问题