So I know that Find() is only a List<T> method, whereas First() is an extension for any IEnumerable<T>. I also know that First() will return the first element if no parameter is passed, whereas Find() will throw an exception. Lastly, I know that First() will throw an exception if the element is not found, whereas Find() will return the type’s default value.
I hope that clears up confusion about what I’m actually asking. This is a computer science question and deals with these methods at the computational level. I’ve come to understand that IEnumerable<T> extensions do not always operate as one would expect under the hood. So here’s the Q, and I mean from a “close to the metal” standpoint: What is the difference between Find() and First()?
Here’s some code to provide basic assumptions to operate under for this question.
var l = new List<int> { 1, 2, 3, 4, 5 };
var x = l.First(i => i == 3);
var y = l.Find(i => i == 3);
Is there any actual computational difference between how First() and Find() discover their values in the code above?
Note: Let us ignore things like AsParallel() and AsQueryable() for now.
Here’s the code for
List<T>.Find(from Reflector):And here’s
Enumerable.First:So both methods work roughly the same way: they iterate all items until they find one that matches the predicate. The only noticeable difference is that
Finduses aforloop because it already knows the number of elements, andFirstuses a foreach loop because it doesn’t know it.