11

可能重复:
哪种方法性能更好:.Any() 与 .Count() > 0?

我只是想知道为什么我应该使用Any()而不是Count()?,如果我们以msdn为例:

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}
class Person
{
    public string LastName { get; set; }
    public Pet[] Pets { get; set; }
}

public static void AnyEx2()
{
    List<Person> people = new List<Person>
        { new Person { LastName = "Haas",
                       Pets = new Pet[] { new Pet { Name="Barley", Age=10 },
                                          new Pet { Name="Boots", Age=14 },
                                          new Pet { Name="Whiskers", Age=6 }}},
          new Person { LastName = "Fakhouri",
                       Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}},
          new Person { LastName = "Antebi",
                       Pets = new Pet[] { }},
          new Person { LastName = "Philips",
                       Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2},
                                          new Pet { Name = "Rover", Age = 13}} }
        };

    // Determine which people have a non-empty Pet array.
    IEnumerable<string> names = from person in people
                            where person.Pets.AsQueryable().Any()
                            select person.LastName;

    foreach (string name in names)
        Console.WriteLine(name);

    /* This code produces the following output:

       Haas
       Fakhouri
       Philips
    */
}

如果我使用了怎么办:

  IEnumerable<string> names = from person in people
                            where person.Pets.Count() > 0
                            select person.LastName;

它会给出相同的结果!, (我不认为它是为了简短或什么而创建的),有什么功能Any()吗??

4

4 回答 4

19

Any只检查序列是否包含至少一个元素,而Count需要遍历所有元素。这就是区别。Any首选的经典场景Count是:

if (sec.Count() > 0)

对比

if (sec.Any())
于 2012-09-26T13:12:53.763 回答
7

根据隐藏在接口后面的具体实现,可能比. 例如,如果实际上有 LINQ-to-SQL 或其他一些数据库提供程序,则可能是检查表中至少 1条记录或必须计算数据库中的每条记录之间的区别。IEnumerable<>AnyCount

然而,在我看来,更重要的原因是usingAny()比检查更能表达你的意图Count() > 0。它询问“有任何物品吗?” 而不是“找出有多少项目。这个数字是否大于零”。对你来说,“有什么物品吗?”的哪个翻译更自然??

于 2012-09-26T13:19:59.353 回答
2

实际上,这取决于。

如果您的集合是 IEnumerable 的形式,则 Count() 方法将遍历所有元素,而 Any() 则不必这样做。因此,对于可枚举, Any() 将具有(潜在的显着)性能优势。

但是,在您的示例中,Pets 是一个数组,因此您最好使用 .Length 而不是 .Count()。在这种情况下,性能不会有显着差异。

于 2012-09-26T13:20:11.787 回答
2

要获得计数,代码必须遍历整个序列。在一个长的、延迟执行的序列上,这可能会花费大量时间。由于我只想知道序列是否包含一个或多个元素,因此使用 Any() 扩展方法的计算效率更高。

阅读Eric Lippert 的博客

还可以阅读Count() 和 Count 属性

于 2012-09-26T13:14:04.257 回答