Count 属性与 Count() 方法?

发布于 2024-12-13 12:04:53 字数 343 浏览 1 评论 0原文

使用集合时,我有两种方法来获取对象的数量; Count (属性)和 Count() (方法)。有谁知道主要区别是什么?

我可能是错的,但我总是在任何条件语句中使用 Count 属性,因为我假设 Count() 方法对集合执行某种查询,其中因为 Count 必须在我“获取”之前就已分配。但这只是一个猜测——我不知道如果我错了,性能是否会受到影响。

编辑:出于好奇,如果集合为 null,Count() 会抛出异常吗?因为我非常确定 Count 属性只会返回 0。

Working with a collection I have the two ways of getting the count of objects; Count (the property) and Count() (the method). Does anyone know what the key differences are?

I might be wrong, but I always use the Count property in any conditional statements because I'm assuming the Count() method performs some sort of query against the collection, where as Count must have already been assigned prior to me 'getting.' But that's a guess - I don't know if performance will be affected if I'm wrong.

EDIT: Out of curiosity then, will Count() throw an exception if the collection is null? Because I'm pretty sure the Count property simply returns 0.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

深海蓝天 2024-12-20 12:04:53

反编译 Count() 扩展方法的源代码显示,它测试该对象是否是 ICollection(通用或其他),如果是,则简单地返回底层 Count 属性:

因此,如果您的代码访问 Count 而不是调用 Count(),您可以绕过类型检查 - 理论上的性能优势,但我怀疑它会成为一名引人注目的人!

// System.Linq.Enumerable
public static int Count<TSource>(this IEnumerable<TSource> source)
{
    checked
    {
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
        ICollection<TSource> collection = source as ICollection<TSource>;
        if (collection != null)
        {
            return collection.Count;
        }
        ICollection collection2 = source as ICollection;
        if (collection2 != null)
        {
            return collection2.Count;
        }
        int num = 0;
        using (IEnumerator<TSource> enumerator = source.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                num++;
            }
        }
        return num;
    }
}

Decompiling the source for the Count() extension method reveals that it tests whether the object is an ICollection (generic or otherwise) and if so simply returns the underlying Count property:

So, if your code accesses Count instead of calling Count(), you can bypass the type checking - a theoretical performance benefit but I doubt it would be a noticeable one!

// System.Linq.Enumerable
public static int Count<TSource>(this IEnumerable<TSource> source)
{
    checked
    {
        if (source == null)
        {
            throw Error.ArgumentNull("source");
        }
        ICollection<TSource> collection = source as ICollection<TSource>;
        if (collection != null)
        {
            return collection.Count;
        }
        ICollection collection2 = source as ICollection;
        if (collection2 != null)
        {
            return collection2.Count;
        }
        int num = 0;
        using (IEnumerator<TSource> enumerator = source.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                num++;
            }
        }
        return num;
    }
}
凉薄对峙 2024-12-20 12:04:53

性能只是选择其中之一的原因之一。选择 .Count() 意味着您的代码将更加通用。我曾经有过重构一些代码的情况,这些代码不再生成集合,而是生成一些更通用的代码,例如 IEnumerable,但其他代码因此而崩溃,因为它依赖于 .Count 并且我不得不将其更改为 .Count()。如果我决定在任何地方都使用 .Count(),那么代码可能会更具可重用性和可维护性。如果可以的话,通常选择使用更通用的接口是最好的选择。通过更通用,我的意思是由更多类型实现的更简单的接口,从而使代码之间具有更大的兼容性。

我并不是说 .Count() 更好,我只是说还有其他考虑因素更多地涉及您正在编写的代码的可重用性。

Performance is only one reason to choose one or the other. Choosing .Count() means that your code will be more generic. I've had occasions where I refactored some code that no longer produced a collection, but instead something more generic like an IEnumerable, but other code broke as a result because it depended on .Count and I had to change it to .Count(). If I made a point to use .Count() everywhere, the code would likely be more reusable and maintainable. Usually opting to utilize the more generic interfaces if you can get away with it is your best bet. By more generic, I mean the simpler interface that is implemented by more types, and thus netting you greater compatibility between code.

I'm not saying .Count() is better, I'm just saying there's other considerations that deal more with the reusability of the code you are writing.

风苍溪 2024-12-20 12:04:53

.Count() 方法可能足够聪明,或者知道有问题的类型,如果是这样,它可能使用底层的< code>.Count 属性。

话又说回来,可能不会。

我想说,可以安全地假设,如果集合本身具有 .Count 属性,那么在性能方面这将是您的最佳选择。

如果 .Count() 方法不知道该集合,它将对其进行枚举,这将是一个 O(n) 操作。

The .Count() method might be smart enough, or know about the type in question, and if so, it might use the underlying .Count property.

Then again, it might not.

I would say it is safe to assume that if the collection has a .Count property itself, that's going to be your best bet when it comes to performance.

If the .Count() method doesn't know about the collection, it will enumerate over it, which will be an O(n) operation.

相思碎 2024-12-20 12:04:53

简短版本:如果您可以在 Count 属性和 Count() 方法之间进行选择,请始终选择该属性。

差异主要在于操作效率。所有公开 Count 属性的 BCL 集合都以 O(1) 的方式执行此操作。 Count() 方法虽然可以而且通常会花费 O(N) 的成本。对于某些实现,有一些检查尝试使其达到 O(1),但这绝不是保证的。

Short Version: If you have the choice between a Count property and a Count() method always choose the property.

The difference is mainly around the efficiency of the operation. All BCL collections which expose a Count property do so in an O(1) fashion. The Count() method though can, and often will, cost O(N). There are some checks to try and get it to O(1) for some implementations but it's by no means guaranteed.

傻比既视感 2024-12-20 12:04:53

Count() 方法是适用于任何 IEnumerable 的 LINQ 方法。您可能期望 Count() 方法迭代整个集合来查找计数,但我相信 LINQ 代码实际上有一些优化来检测 Count 属性是否存在,如果存在,则使用它。

所以他们应该做几乎相同的事情。 Count 属性可能稍微好一些,因为不需要在那里进行类型检查。

The Count() method is the LINQ method that works on any IEnumerable<>. You would expect the Count() method to iterate over the whole collection to find the count, but I believe the LINQ code actually has some optimizations in there to detect if a Count property exists and if so use that.

So they should both do almost identical things. The Count property is probably slightly better since there doesn't need to be a type check in there.

戏蝶舞 2024-12-20 12:04:53

Count() 方法是一种扩展方法,它迭代 IEnumerable>> 的每个元素并返回其中有多少个元素。如果 IEnumerable 的实例实际上是 List<>,那么它会被优化为返回 Count 属性,而不是迭代所有元素。

Count() method is an extension method that iterates each element of an IEnumerable<> and returns how many elements are there. If the instance of IEnumerable is actually a List<>, so it's optimized to return the Count property instead of iterating all elements.

揪着可爱 2024-12-20 12:04:53

Count() 是 LINQ 的扩展方法 - CountList(实际的 .NET 集合对象)上的一个属性。

因此,Count() 几乎总是会变慢,因为它将枚举集合/可查询对象。在列表、队列、堆栈等上,使用Count。或者对于数组 - Length

Count() is there as an extension method from LINQ - Count is a property on Lists, actual .NET collection objects.

As such, Count() will almost always be slower, since it will enumerate the collection / queryable object. On a list, queue, stack etc, use Count. Or for an array - Length.

混浊又暗下来 2024-12-20 12:04:53

如果存在 CountLength 属性,您应该始终首选该属性而不是 Count() 方法,后者通常会迭代整个集合进行计数内的元素数量。例如,当 Count() 方法针对 LINQ to SQL 或 LINQ to Entities 源时会出现例外,在这种情况下,它将针对数据源执行计数查询。即使如此,如果有一个 Count 属性,您可能会更喜欢它,因为它可能需要做的工作较少。

If there is a Count or Length property, you should always prefer that to the Count() method, which generally iterates the entire collection to count the number of elements within. Exceptions would be when the Count() method is against a LINQ to SQL or LINQ to Entities source, for example, in which case it would perform a count query against the datasource. Even then, if there is a Count property, you would want to prefer that, since it likely has less work to do.

反目相谮 2024-12-20 12:04:53

Count() 方法对 ICollection 进行了优化,从而导致调用 Count 属性。在这种情况下,性能可能没有显着差异。

不过,除了 ICollection 之外,还有其他类型可以替代 Count() 扩展方法。此代码分析性能规则针对以下类型触发。

CA1829:使用长度/计数因此

System.Array
System.Collections.Immutable.ImmutableArray<T>
System.Collections.ICollection
System.Collections.Generic.ICollection<T>
System.Collections.Generic.IReadOnlyCollection<T>

,我们应该使用 CountLength 属性(如果它们可用)并回退到 Count() 扩展否则方法。

The Count() method has an optimisation for ICollection<T> which results in the Count property being called. In this case there is probably no significant difference in performance.

There are types other than ICollection<T> which have more efficient alternatives to the Count() extension method though. This code analysis performance rule fires on the following types.

CA1829: Use Length/Count property instead of Enumerable.Count method

System.Array
System.Collections.Immutable.ImmutableArray<T>
System.Collections.ICollection
System.Collections.Generic.ICollection<T>
System.Collections.Generic.IReadOnlyCollection<T>

So, we should use Count and Length properties if they are available and fallback to the Count() extension method otherwise.

隔岸观火 2024-12-20 12:04:53

.Count 是集合的一个属性,用于获取集合中的元素。与 .Count() 不同,它是 LINQ 的扩展方法,用于计算元素的数量。

一般来说,.Count.Count() 更快,因为它不需要创建和枚举 LINQ 查询的开销。

最好使用 .Count 属性,除非您需要 .Count() 方法提供的附加功能,例如指定过滤谓词的能力,例如

int count = numbers.Count(n => n.Id == 100);

.Count is a property of a collection and gets the elements in the collection. Unlike .Count() which is an extension method for LINQ and counts the number of elements.

Generally .Count is faster than .Count() because it does not require the overhead of creating and enumerating a LINQ query.

It's better to use the .Count property unless you need the additional functionality provided by the .Count() method, such as the ability to specify a filtering predicate, e.g.

int count = numbers.Count(n => n.Id == 100);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文