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

前端 未结 7 1829
南旧
南旧 2020-11-27 11:31

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 ot

相关标签:
7条回答
  • 2020-11-27 12:38

    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.

    so say you have List of Test class having id and name properties.

     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 2 visits Find needed to give result , but if you use Where().FirstOrDefault() we will be visiting all records and then we get results.

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

    0 讨论(0)
提交回复
热议问题