I've searched around and haven't really found a clear answer as to when you'd want to use .First
and when you'd want to use .FirstOrDefault
with LINQ.
When would you want to use
.First
? Only when you'd want to catch the exception if no results where returned?var result = List.Where(x => x == "foo").First();
And when would you want to use
.FirstOrDefault
? When you'd always want the default type if no result?var result = List.Where(x => x == "foo").FirstOrDefault();
And for that matter, what about Take?
var result = List.Where(x => x == "foo").Take(1);
First()
When you know that result contain more than 1 element expected and you should only the first element of sequence.
FirstOrDefault()
FirstOrDefault() is just like First() except that, if no element match the specified condition than it returns default value of underlying type of generic collection. It does not throw InvalidOperationException if no element found. But collection of element or a sequence is null than it throws an exception.
Sorry for posting answer to old post. detail and good explanation so please read below urls http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/
http://www.dotnet-tricks.com/Tutorial/linq/E23I160714-Understanding-Single,-SingleOrDefault,-First-and-FirstOrDefault.html
http://www.c-sharpcorner.com/UploadFile/3d39b4/singleordefault-and-firstordefault-methods-in-linq-to-sql/