FirstOrDefault LINQ C# Example

When we want to find only one object from the linq query result, we use First and FirstOrDefault method, here we learn how to use First and FirstOrDefault Method in LINQ!

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

LINQ FirstOrDefault example

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.

 
Firstordefault in linq query: linq first and firstordefault example c#
LINQ (language integrated query) allow you to write query on database objects like ado.net, 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 Asp.net MVC Course