Moh*_*rag 11 c# linq asp.net linq-to-entities entity-framework
我只是想知道为什么我应该使用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
*/
}
Run Code Online (Sandbox Code Playgroud)
如果我使用了怎么办:
IEnumerable<string> names = from person in people
where person.Pets.Count() > 0
select person.LastName;
Run Code Online (Sandbox Code Playgroud)
它会给出相同的结果!,(我不认为它是为了简短或其他东西而创造的),是否有任何功能Any()
?
Cla*_*edi 19
Any
只检查序列是否包含至少一个元素,同时Count
需要迭代所有元素.这就是区别.一个经典的场景,Any
首选Count
是这样的:
if (sec.Count() > 0)
Run Code Online (Sandbox Code Playgroud)
VS
if (sec.Any())
Run Code Online (Sandbox Code Playgroud)
根据究竟是什么实现的IEnumerable<>
是躲在背后的接口,Any
可能会大大快于Count
.例如,实际上有LINQ-to-SQL或其他一些数据库提供程序,它可能是检查一个表至少1条记录,或者必须计算数据库中的每条记录.
但是,在我看来,更重要的原因是使用Any()
表达你的INTENT比检查更好Count() > 0
.它问"有什么物品吗?" 而不是"找出有多少项目.这个数字大于零".对你来说,"有没有任何物品更自然地翻译?" ?
归档时间: |
|
查看次数: |
4843 次 |
最近记录: |