Free Web Development Online Tutorials, Learn to Code
Learn LINQ with C#, Language Integrated query with different Data Source

FirstOrDefault LINQ C# Example

How to use First and FirstOrDefault Method in LINQ!

LINQ FirstOrDefault

First and FirstOrDefault in LINQ are Element Operators, Both method returns first element from the collection object or data source.

First and FirstOrDefault are actually extension method from IQueryable and IEnmuerable

This is how you can use FirstOrDefault method in LINQ

_student = context.tbStudents
.Where(s => s.studentId == id)
.FirstOrDefault<tbStudent>();

Here is another example of FirstOrDefault

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

Example of using First 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 First and FirstOrDefault

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

Comment
Name
Email
Website
Subscribe
 
Learn LINQ .Net

FirstOrDefault method in LINQ C#, LINQ FirstOrDefault Example

linq Interview Questions Answers

LINQ C# examples | Join Asp.net MVC Course