Tuesday, October 9, 2012

When to use .First and .FirstOrDefault with LINQ?

When to use .First() and when to use .FirstOrDefault() with LINQ?

This is a frequent question among .NET developers who use LINQ.
Many of the developers keep coding with this doubt being uncleared in the back of their mind.
This is a very simple and straight forward question and solution.

Use .First() when you are pretty use that the LINQ query will definitely return at least one element in a sequence. In this case First() works pretty well and it will return the top 1 element from the resulting enumeration. But the sad part is when there is nothing returned executing the LINQ expression. In which case it will throw and exception. Practicing to catch the exception and always using only .First() is a very bad practice as it will affect the performance.

Use .FirstOrDefault() in the case where you cannot guarantee a result when executing a LINQ statement. In this case it gracefully returns the default value depending on the type. That is Null for reference types and the default values for primitive types. For example the default value for int is 0;

No comments:

Post a Comment