How to check if IEnumerable is null or empty?

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

    I built this off of the answer by @Matt Greer

    He answered the OP's question perfectly.

    I wanted something like this while maintaining the original capabilities of Any while also checking for null. I'm posting this in case anyone else needs something similar.

    Specifically I wanted to still be able to pass in a predicate.

    public static class Utilities
    {
        /// 
        /// Determines whether a sequence has a value and contains any elements.
        /// 
        /// The type of the elements of source.
        /// The  to check for emptiness.
        /// true if the source sequence is not null and contains any elements; otherwise, false.
        public static bool AnyNotNull(this IEnumerable source)
        {
            return source?.Any() == true;
        }
    
        /// 
        /// Determines whether a sequence has a value and any element of a sequence satisfies a condition.
        /// 
        /// The type of the elements of source.
        /// An  whose elements to apply the predicate to.
        /// A function to test each element for a condition.
        /// true if the source sequence is not null and any elements in the source sequence pass the test in the specified predicate; otherwise, false.
        public static bool AnyNotNull(this IEnumerable source, Func predicate)
        {
            return source?.Any(predicate) == true;
        }
    }
    

    The naming of the extension method could probably be better.

提交回复
热议问题