Single and SingleOrDefault LINQ C# Example

SingleOrDefault and Single method is used when we want to select single item from collection list in LINQ query.


Single and SingleOrDefault in LINQ are Element Operators, returns one element of a sequence, or default value if sequence is empty, this method will throw an exception if there is more than one element in sequence

LINQ SingleOrDefault C#

Single and SingleOrDefault are actually extension method from IQueryable and IEnmuerable

SingleOrDefault and FirstOrDefault difference

Let's understand difference between SingleOrDefault and FirstOrDefault, Now you may think when to use SingleOrDefault and how different from FirstOrDefault?

When you sure that there is only one record in database, for example if you are querying on primary key any key that will return one result only, in such scenario you can use SingleOrDefault.
But, if you know there will be multiple result and you want just first data from collection, then use FirstOrDefault.

This is how you can use SingleOrDefault method in LINQ

_student = context.tbStudents
.Where(s => s.studentId == id)

Here is another example of SingleOrDefault

var student = (from s in context.tbStudents             
where s.FullName == "Anu"
select s).SingleOrDefault<tbStudent>();

Example of using Single method

_student = context.tbStudents
.Where(s => s.studentId == id)

If there is no element found then it will throw an exception.

Difference between Single and SingleOrDefault

Both fetch the single element from the collection object or source, but Single will throw and exception if no element found, when SingleOrDefault will not throw any error, it will return the default value of that data type.

Single and SingleOrDefault LINQ C#
LINQ (language integrated query) allow you to write query on database objects like, entity framework etc, LINQ is type safe, easy to convert database object to list objects and business objects in secure and scalable way.
linq Interview Questions Answers
LINQ C# examples | Join MVC Course