Free Web Development Online Tutorials, Learn to Code
Learn LINQ with C#, LINQ Single SingleOrDefault Method, Difference between Single and SingleOrDefault

Single and SingleOrDefault LINQ C# Example

LINQ SingleOrDefault C#

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

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)
.SingleOrDefault<tbStudent>();

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)
.First<tbStudent>();

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.

Comment
Name
Email
Website
Subscribe
 
Learn LINQ .Net

Single and SingleOrDefault LINQ C#

linq Interview Questions Answers

LINQ C# examples | Join Asp.net MVC Course