我为什么要使用Any方法而不是Count?

时间:2012-09-26 13:09:43

标签: c# asp.net linq entity-framework linq-to-entities

  

可能重复:
  Which method performs better: .Any() vs .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 个答案:

答案 0 :(得分:19)

Any只检查序列是否包含至少一个元素,而Count需要迭代所有元素。这就是区别。 Any优先于Count的经典场景是:

if (sec.Count() > 0)

VS

if (sec.Any())

答案 1 :(得分:6)

完全取决于 IEnumerable<>实现隐藏在界面后面,Any可能比Count快得多。例如,实际上有LINQ-to-SQL或其他一些数据库提供者,可能是检查至少1 记录的表,或者必须计算每个记录在数据库中。

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

答案 2 :(得分:2)

要获得计数,代码必须遍历整个序列。在漫长而懒惰的序列上,这可能需要很长时间。由于我只想知道序列是否包含一个或多个元素,因此使用Any()扩展方法在计算上更有效。

阅读Eric Lippert's Blog

也是用户阅读Count() and Count property

答案 3 :(得分:2)

实际上,这取决于。

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

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

相关问题