查找()与凡()。FirstOrDefault() [英] Find() vs. Where().FirstOrDefault()
问题描述
我经常看到有人使用 Where.FirstOrDefault()
做搜索和抓取的第一要素。为什么不使用查找()
?有一个优点是其他?我不能告诉区别。
命名空间LinqFindVsWhere
{
类节目
{
静态无效的主要(字串[] args)
{
清单<串GT;名单=新名单,LT;串>();
list.AddRange(新的String []
{
ITEM1
ITEM2
项目3
ITEM4
}); 字符串ITEM2 = list.Find(X => X ==ITEM2);
Console.WriteLine(?ITEM2 == NULL未发现:发现);
串item3的= list.Where(X =&X的催化剂==项目3)FirstOrDefault();
Console.WriteLine(?项目3 == NULL未发现:发现);
Console.ReadKey();
}
}
}
哪里是在的IEnumerable&LT的
? (反问)。查找
方法; T>
的其中,
和 FirstOrDefault
方法适用对多种类型的序列,包括名单,LT ; T>
, T []
,收藏< T>
等任何序列实现的IEnumerable< T>
可以使用这些方法。 T> 查找
仅用于名单,LT是可用的。的方法一般都比较适用,然后以上的可重用的的和有较大影响。
我想我的下一个问题是为什么他们加入找到所有。这是一个很好的提示。我能想到的唯一的事情是,FirstOrDefault可以返回null以外不同的默认值。否则,它只是似乎是一个毫无意义的除了
块引用>
查找
在列表< T>
predates其他方法。列表< T>
与仿制药加在.NET 2.0和查找
是该类的API的一部分。其中,
和FirstOrDefault
添加为扩展方法为的IEnumerable< T>
使用LINQ,这是以后的.NET版本。我不能肯定地说,如果LINQ的与2.0版本中存在的查找
绝不会被添加,但可以说是许多其他功能,排在前面.NET的情况下这是过时或更高版本的冗余版本。I often see people using
Where.FirstOrDefault()
to do a search and grab the first element. Why not just useFind()
? Is there an advantage to the other? I couldn't tell a difference.namespace LinqFindVsWhere { class Program { static void Main(string[] args) { List<string> list = new List<string>(); list.AddRange(new string[] { "item1", "item2", "item3", "item4" }); string item2 = list.Find(x => x == "item2"); Console.WriteLine(item2 == null ? "not found" : "found"); string item3 = list.Where(x => x == "item3").FirstOrDefault(); Console.WriteLine(item3 == null ? "not found" : "found"); Console.ReadKey(); } } }
解决方案Where is the
Find
method onIEnumerable<T>
? (Rhetorical question.)The
Where
andFirstOrDefault
methods are applicable against multiple kinds of sequences, includingList<T>
,T[]
,Collection<T>
, etc. Any sequence that implementsIEnumerable<T>
can use these methods.Find
is available only for theList<T>
. Methods that are generally more applicable, are then more reusable and have a greater impact.I guess my next question would be why did they add the find at all. That is a good tip. The only thing I can think of is that the FirstOrDefault could return a different default value other than null. Otherwise it just seems like a pointless addition
Find
onList<T>
predates the other methods.List<T>
was added with generics in .NET 2.0, andFind
was part of the API for that class.Where
andFirstOrDefault
were added as extension methods forIEnumerable<T>
with Linq, which is a later .NET version. I cannot say with certainty that if Linq existed with the 2.0 release thatFind
would never have been added, but that is arguably the case for many other features that came in earlier .NET versions that were made obsolete or redundant by later versions.这篇关于查找()与凡()。FirstOrDefault()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!