gpt4 book ai didi

c# - 为什么我应该使用 Any 方法而不是 Count?

转载 作者:可可西里 更新时间:2023-11-01 08:33:18 24 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
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() 有什么功能吗??

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com