确定列表是否为空的“最佳”方法(同时考虑速度和可读性)是什么?即使列表是类型 IEnumerable<T> 并且没有 Count 属性。

现在我正在这之间折腾:

if (myList.Count() == 0) { ... }

和这个:

if (!myList.Any()) { ... }

我的猜测是第二个选项更快,因为它一看到第一个项目就会返回结果,而第二个选项(对于 IEnumerable)将需要访问每个项目才能返回计数。

话虽这么说,第二个选项对您来说可读吗?你更喜欢哪个?或者你能想出更好的方法来测试空列表吗?

编辑 @lassevk 的响应似乎是最合乎逻辑的,再加上一些运行时检查以在可能的情况下使用缓存计数,如下所示:

public static bool IsEmpty<T>(this IEnumerable<T> list)
{
    if (list is ICollection<T>) return ((ICollection<T>)list).Count == 0;

    return !list.Any();
}
有帮助吗?

解决方案

你可以这样做:

public static Boolean IsEmpty<T>(this IEnumerable<T> source)
{
    if (source == null)
        return true; // or throw an exception
    return !source.Any();
}

编辑: :请注意,如果底层源实际上具有快速 Count 属性,则仅使用 .Count 方法会很快。上面的有效优化是检测一些基本类型并简单地使用这些基类型的 .Count 属性,而不是 .Any() 方法,但如果无法保证,则回退到 .Any() 。

其他提示

我会对您似乎已经确定的代码做一点小小的补充:还检查 ICollection, ,因为这甚至是由一些非过时的泛型类实现的(即, Queue<T>Stack<T>)。我也会用 as 代替 is 因为它更惯用并且 已被证明更快.

public static bool IsEmpty<T>(this IEnumerable<T> list)
{
    if (list == null)
    {
        throw new ArgumentNullException("list");
    }

    var genericCollection = list as ICollection<T>;
    if (genericCollection != null)
    {
        return genericCollection.Count == 0;
    }

    var nonGenericCollection = list as ICollection;
    if (nonGenericCollection != null)
    {
        return nonGenericCollection.Count == 0;
    }

    return !list.Any();
}

LINQ 本身必须以某种方式围绕 Count() 方法进行一些认真的优化。

这让你感到惊讶吗?我想对于 IList 实施, Count 只需直接读取元素数量即可 Any 必须查询 IEnumerable.GetEnumerator 方法,创建实例并调用 MoveNext 至少一次。

/编辑@马特:

我只能假设 IEnumerable 的 Count() 扩展方法正在执行如下操作:

是的,当然可以。这就是我的意思。实际上,它使用 ICollection 代替 IList 但结果是一样的。

我刚刚写了一个快速测试,试试这个:

 IEnumerable<Object> myList = new List<Object>();

 Stopwatch watch = new Stopwatch();

 int x;

 watch.Start();
 for (var i = 0; i <= 1000000; i++)
 {
    if (myList.Count() == 0) x = i; 
 }
 watch.Stop();

 Stopwatch watch2 = new Stopwatch();

 watch2.Start();
 for (var i = 0; i <= 1000000; i++)
 {
     if (!myList.Any()) x = i;
 }
 watch2.Stop();

 Console.WriteLine("myList.Count() = " + watch.ElapsedMilliseconds.ToString());
 Console.WriteLine("myList.Any() = " + watch2.ElapsedMilliseconds.ToString());
 Console.ReadLine();

第二个几乎慢了三倍:)

使用堆栈或数组或其他场景再次尝试秒表测试,它实际上取决于看起来的列表类型 - 因为它们证明 Count 速度较慢。

所以我想这取决于您使用的列表类型!

(只是指出,我在列表中放入了 2000 多个对象,并且计数仍然更快,与其他类型相反)

List.Count 根据微软的文档,是 O(1):
http://msdn.microsoft.com/en-us/library/27b47ht3.aspx

所以只需使用 List.Count == 0 它比查询快得多

这是因为它有一个名为 Count 的数据成员,每当从列表中添加或删除某些内容时,该成员都会更新,因此当您调用 List.Count 它不必遍历每个元素来获取它,它只是返回数据成员。

如果您有多个项目,第二个选项会快得多。

  • Any() 找到 1 件商品后立即返回。
  • Count() 必须继续浏览整个列表。

例如,假设枚举有 1000 个项目。

  • Any() 将检查第一个,然后返回 true。
  • Count() 遍历整个枚举后将返回 1000。

如果您使用其中一个谓词覆盖,情况可能会更糟 - Count() 仍然必须检查每一项,即使只有一个匹配项。

您习惯使用 Any one - 它确实有意义且可读。

需要注意的是,如果您有一个列表,而不仅仅是一个 IEnumerable,那么请使用该列表的 Count 属性。

@Konrad令我惊讶的是,在我的测试中,我将列表传递给接受的方法 IEnumerable<T>, ,因此运行时无法通过调用 Count() 扩展方法来优化它 IList<T>.

我只能假设 IEnumerable 的 Count() 扩展方法正在执行如下操作:

public static int Count<T>(this IEnumerable<T> list)
{
    if (list is IList<T>) return ((IList<T>)list).Count;

    int i = 0;
    foreach (var t in list) i++;
    return i;
}

...换句话说,针对特殊情况进行一些运行时优化 IList<T>.

/编辑@Konrad +1 伙伴 - 你说得对,更有可能在 ICollection<T>.

好吧,那么这个呢?

public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
    return !enumerable.GetEnumerator().MoveNext();
}

编辑:我刚刚意识到有人已经勾画出了这个解决方案。有人提到 Any() 方法会执行此操作,但为什么不自己执行呢?问候

另一个想法:

if(enumerable.FirstOrDefault() != null)

不过我更喜欢 Any() 方法。

这对于使其与实体框架一起使用至关重要:

var genericCollection = list as ICollection<T>;

if (genericCollection != null)
{
   //your code 
}

如果我使用 Count() 检查 Linq 在数据库中执行“SELECT COUNT(*)..”,但我需要检查结果是否包含数据,我决定引入 FirstOrDefault() 而不是 Count();

var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()

if (cfop.Count() > 0)
{
    var itemCfop = cfop.First();
    //....
}

var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()

var itemCfop = cfop.FirstOrDefault();

if (itemCfop != null)
{
    //....
}
private bool NullTest<T>(T[] list, string attribute)

    {
        bool status = false;
        if (list != null)
        {
            int flag = 0;
            var property = GetProperty(list.FirstOrDefault(), attribute);
            foreach (T obj in list)
            {
                if (property.GetValue(obj, null) == null)
                    flag++;
            }
            status = flag == 0 ? true : false;
        }
        return status;
    }


public PropertyInfo GetProperty<T>(T obj, string str)

    {
        Expression<Func<T, string, PropertyInfo>> GetProperty = (TypeObj, Column) => TypeObj.GetType().GetProperty(TypeObj
            .GetType().GetProperties().ToList()
            .Find(property => property.Name
            .ToLower() == Column
            .ToLower()).Name.ToString());
        return GetProperty.Compile()(obj, str);
    }

这是我对丹涛答案的实现,允许使用谓词:

public static bool IsEmpty<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    if (source == null) throw new ArgumentNullException();
    if (IsCollectionAndEmpty(source)) return true;
    return !source.Any(predicate);
}

public static bool IsEmpty<TSource>(this IEnumerable<TSource> source)
{
    if (source == null) throw new ArgumentNullException();
    if (IsCollectionAndEmpty(source)) return true;
    return !source.Any();
}

private static bool IsCollectionAndEmpty<TSource>(IEnumerable<TSource> source)
{
    var genericCollection = source as ICollection<TSource>;
    if (genericCollection != null) return genericCollection.Count == 0;
    var nonGenericCollection = source as ICollection;
    if (nonGenericCollection != null) return nonGenericCollection.Count == 0;
    return false;
}
List<T> li = new List<T>();
(li.First().DefaultValue.HasValue) ? string.Format("{0:yyyy/MM/dd}", sender.First().DefaultValue.Value) : string.Empty;

myList.ToList().Count == 0. 。就这样

这个扩展方法对我有用:

public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
    try
    {
        enumerable.First();
        return false;
    }
    catch (InvalidOperationException)
    {
        return true;
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top