C#是否具有IsNullOrEmpty用于List/IEnumerable? [英] Does C# have IsNullOrEmpty for List/IEnumerable?

查看:265
本文介绍了C#是否具有IsNullOrEmpty用于List/IEnumerable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道通常空列表比NULL更可取.但是我将返回NULL,主要有两个原因

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

  1. 我必须显式检查并处理null值,以避免bug和攻击.
  2. 随后很容易执行??操作以获取返回值.
  1. I have to check and handle null values explicitly, avoiding bugs and attacks.
  2. It is easy to perform ?? operation afterwards to get a return value.

对于字符串,我们具有IsNullOrEmpty. C#本身是否有任何 对List或IEnumerable做相同的事情?

For strings, we have IsNullOrEmpty. Is there anything from C# itself doing the same thing for List or IEnumerable?

推荐答案

框架中没有任何内容,但这是一种非常简单的扩展方法.

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

请参见此处

/// <summary>
    /// Determines whether the collection is null or contains no elements.
    /// </summary>
    /// <typeparam name="T">The IEnumerable type.</typeparam>
    /// <param name="enumerable">The enumerable, which may be null or empty.</param>
    /// <returns>
    ///     <c>true</c> if the IEnumerable is null or empty; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> 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<T>;
        if (collection != null)
        {
            return collection.Count < 1;
        }
        return !enumerable.Any(); 
    }

出于性能方面的考虑,Daniel Vaughan采取了额外的步骤将其强制转换为ICollection.我本来不想做的事.

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

这篇关于C#是否具有IsNullOrEmpty用于List/IEnumerable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆