C# Find() 与 Where().FirstOrDefault()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9335015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:57:20  来源:igfitidea点击:

Find() vs. Where().FirstOrDefault()

c#linqlinq-to-objects

提问by KingOfHypocrites

I often see people using Where.FirstOrDefault()to do a search and grab the first element. Why not just use Find()? Is there an advantage to the other? I couldn't tell a difference.

我经常看到人们使用Where.FirstOrDefault()搜索并获取第一个元素。为什么不直接使用Find()?对方有优势吗?我说不出有什么区别。

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();
        }
    }
}

采纳答案by Anthony Pegram

Where is the Findmethod on IEnumerable<T>? (Rhetorical question.)

在哪里Find上的方法IEnumerable<T>?(反问。)

The Whereand FirstOrDefaultmethods are applicable against multiple kinds of sequences, including List<T>, T[], Collection<T>, etc. Any sequence that implements IEnumerable<T>can use these methods. Findis available only for the List<T>. Methods that are generally more applicable, are then more reusableand have a greater impact.

WhereFirstOrDefault方法可应用于对多种序列,包括List<T>T[]Collection<T>等。任何顺序实现IEnumerable<T>可以使用这些方法。Find仅适用于List<T>. 通常更适用的方法,然后更可重用并且具有更大的影响。

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 。这是一个很好的提示。我唯一能想到的是 FirstOrDefault 可以返回一个不同的默认值而不是 null。否则它似乎只是一个毫无意义的添加

Findon List<T>predates the other methods. List<T>was added with generics in .NET 2.0, and Findwas part of the API for that class. Whereand FirstOrDefaultwere added as extension methods for IEnumerable<T>with Linq, which is a later .NET version. I cannot say with certainty that if Linq existed with the 2.0 release that Findwould 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.

FindList<T>早于其他方法。List<T>在 .NET 2.0 中添加了泛型,并且Find是该类 API 的一部分。WhereFirstOrDefault作为IEnumerable<T>with Linq 的扩展方法添加,后者是更高的 .NET 版本。我不能肯定地说,如果 Linq 与Find永远不会添加的 2.0 版本一起存在,但可以说是早期 .NET 版本中出现的许多其他功能的情况,这些功能在以后的版本中已经过时或冗余。

回答by penartur

Findis only implementedin List<T>, while Where().FirstOrDefault()works with all IEnumerable<T>.

Find仅在 中实现List<T>,而Where().FirstOrDefault()适用于所有IEnumerable<T>.

回答by digiben

I just found out today, doing some tests on a list of 80K objects and found that Find()can be up to 1000% faster than using a Wherewith FirstOrDefault(). I didn't know that until testing a timer before and after each all. Sometimes it was the same time, otherwise it was faster.

我今天才发现,对 80K 个对象的列表进行了一些测试,发现它Find()比使用Wherewith快 1000% FirstOrDefault()。直到在每次之前和之后测试计时器之前,我都不知道这一点。有时是相同的时间,否则会更快。

回答by Chalky

There is a very important difference if the source of the data is Entity Framework: Findwill find entities in the 'added' state that are not yet persisted, but Wherewill not. This is by design.

如果数据源是实体框架,则有一个非常重要的区别: Find将找到尚未持久化但Where不会持久化的处于“已添加”状态的实体。这是设计使然。

回答by M Muneeb Ijaz

in addition to Anthony answer Where()visit through all records and then return result(s) while Find()dont need to traverse through all records if predicate match with given predicate.

除了安东尼回答 Where()访问所有记录,然后返回结果,Find()如果谓词与给定谓词匹配,则不需要遍历所有记录。

so say you have List of Test class having idand nameproperties.

所以说你有测试类的列表idname属性。

 List<Test> tests = new List<Test>();
 tests.Add(new Test() { Id = 1, Name = "name1" });
 tests.Add(new Test() { Id = 2, Name = "name2" });
 tests.Add(new Test() { Id = 3, Name = "name3" });
 tests.Add(new Test() { Id = 4, Name = "name2" }); 
 var r = tests.Find(p => p.Name == "name2");
 Console.WriteLine(r.Id);

Will give output of 2, and only 2visits Find needed to give result , but if you use Where().FirstOrDefault()we will be visiting all records and then we get results.

将给出 的输出2,并且只有2次访问 Find 需要给出结果,但如果您使用Where().FirstOrDefault()我们将访问所有记录,然后我们会得到结果。

So , when you know you only want first result from records in collection Find()will be more suitable then Where().FirtorDefault();

所以,当你知道你只想要集合中记录的第一个结果时Find()会更合适Where().FirtorDefault();

回答by Whiplash

Find()is the IEnumerable equivalent of a FirstOrDefault(). You should not chain both .Where() with .FirstOrDefault()because the .Where()goes through the whole array and then will iterate through that list to find the first item. You save an incredible amount of time by putting your search predicate in the FirstOrDefault()method.

Find()是 IEnumerable 的等效项FirstOrDefault()。您不应该同时链接 .Where() ,.FirstOrDefault()因为它.Where()遍历整个数组,然后遍历该列表以找到第一项。通过将搜索谓词放入FirstOrDefault()方法中,您可以节省大量时间。

Also, I encourage you to read the linked question to this thread to know more about the better performances on using the .Find()in specific scenarios Performance of Find() vs. FirstOrDefault()

此外,我鼓励您阅读此线程的链接问题,以了解更多有关.Find()在特定场景中使用 Find() 与 FirstOrDefault() 性能的更好性能的信息

回答by nguyen khanh

Wow i just watch the EF tutorial from MicrosofToolbox today on Youtube. He did say about using Find() and FirstOrDefault(condition) in query and Find() will search for the data you had performed something on that object( add or edit or delete - but not yet saved into the database ) meanwhile FirstOrDefault will only look for what already have been saved

哇,我今天刚刚在 Youtube 上观看了来自 MicrosofToolbox 的 EF 教程。他确实说过在查询中使用 Find() 和 FirstOrDefault(condition),Find() 将搜索您在该对象上执行某些操作的数据(添加或编辑或删除 - 但尚未保存到数据库中)同时 FirstOrDefault 只会查找已经保存的内容