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