Does C# have IsNullOrEmpty for List/IEnumerable?

前端 未结 10 493
一生所求
一生所求 2020-12-23 11:04

I know generally empty List is more prefer than NULL. But I am going to return NULL, for mainly two reasons

  1. I have to check and handle null values explicitly,
10条回答
  •  萌比男神i
    2020-12-23 11:42

    nothing baked into the framework, but it's a pretty straight forward extension method.

    See here

    /// 
        /// Determines whether the collection is null or contains no elements.
        /// 
        /// The IEnumerable type.
        /// The enumerable, which may be null or empty.
        /// 
        ///     true if the IEnumerable is null or empty; otherwise, false.
        /// 
        public static bool IsNullOrEmpty(this IEnumerable enumerable)
        {
            if (enumerable == null)
            {
                return true;
            }
            /* If this is a list, use the Count property for efficiency. 
             * The Count property is O(1) while IEnumerable.Count() is O(N). */
            var collection = enumerable as ICollection;
            if (collection != null)
            {
                return collection.Count < 1;
            }
            return !enumerable.Any(); 
        }
    

    Daniel Vaughan takes the extra step of casting to ICollection (where possible) for performance reasons. Something I would not have thought to do.

提交回复
热议问题