13 October 2018

difference between FirstOrDefault () and SingleOrDefault()

Recently one of my junior colleague working in .NET asked me about what is the difference between the FirstOrDefault and SingleOrDefault() methods.

Both FirstOrDefault() and SingleOrDefault() are the extension methods on the System.Collections.Generic.IEnumerable defined in System.Linq namespace.

The difference is pretty simple

Enumerable.SingleOrDefault()

SingleOrDefault() method returns the element which matches the condition. If no element matches the condition, then the method returns the default of value of the source type (default(TSource))

If more than one elements match the condition specified, it throw the Exception (InvalidOperationException) Enumerable.FirstOrDefault()

Enumerable.FirstOrDefault()

The way FirstOrDefault() method works is same as the Enumerable.SingleOrDefault() except that it doesn’t throw an exception if more than one element matches the condition. It just returns the first matching record.

How to choose between FirstOrDefault () and SingleOrDefault() methods?

If you know for sure that, there should only be one record present in the collection matching specified condition and presence of more than one record in the collection matching the condition indicates an error, then use the SingleOrDefault() method. So in error conditions, you will rightly get an exception.

If there could be multiple matching records for the specified condition in a collection and just you want the first one, then go ahead and use FirstOrDefault() method.

No comments:

Post a Comment