【发布时间】:2012-09-18 02:59:48
【问题描述】:
我只是想知道为什么我应该使用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() 有什么功能吗??
【问题讨论】:
-
有人递给你一个米袋,问“有米粒吗?”。你是:看看是否有“任何”大米(至少一粒谷物),还是 b:坐下来数一数,只在完成后报告是/否?
-
因为它是命中一个数组,所以“count>0”要快得多(在这种情况下是 11X)。我刚刚对上面的代码进行了基准测试(将 Console.Writeline 移出),“count >0”花费了 1400 个滴答声,而 any() 花费了 15100 个滴答声! [x64,发布模式,未附加调试器]。这是因为 Any() 必须创建和销毁对象。但是,对于数据库连接,通常情况相反。 Any() 通常表现更好。
标签: c# asp.net linq entity-framework linq-to-entities