In this tutorial, we are going to understand what exactly the use Single, SingleOrDefault, First and FirstOrDefault in Linq and what is the use of these functions.

Introduction:

Many people get confused when they have come to a situation where they need to use Single, SingleOrDefault, First and FirstOrDefault. In this, we are going to learn the difference between Single, SingleOrDefault, First and FirstOrDefault and where can we use each of them.

Single, SingleOrDefault, First and FirstOrDefault

Single:

Single specifies that it will return a single element from the collection if a matching element is found from the collection. It will throw an error if none or more than one element found for the given element from the collection.

When to use Single?

Single can be used in a place where only 1 record is expected not zero or more than one.

SingleOrDefault:

SingleOrDefault specifies that it will return a Single element from the collection if a matching element is found from the collection. An exception will raise if more than one element found for the given element in the collection. A default value will return if no match found in the collection.

When to use SingleOrDefault?

SingleOrDefault can be used in a place where 0 Or 1 record is expected.

First:

It returns first matching element from the collection if more than one element is found for that element in the collection. An exception will occur if no matching element is found for that element in the collection.

When to use First:

When duplicate records are expected for the given element in the collection and you want the first one.

FirstOrDefault:

It returns first matching element from the collection if more than one element is found for that element in the collection. A default value will return if no matching element is found for the given element.

When to use FirstOrDefault:

When duplicate records are expected for the given element in the collection and you want the first one. Also in case of no matching element found you want to return empty element.

View More:

Conclusion:

Hope you understand this session about Single, SingleOrDefault, First and FirstOrDefault in Linq and where to use each of them. I would like to have your feedback, Comments and Suggestion.

Thank You.

 

Leave a Comment