LastOrDefault in LINQ C#

LINQ LastOrDefault and Last method is used when we want to select last item from collection list in LINQ query.

Last and LastOrDefault in LINQ are element operators, both method returns last element from the collection object or data source.

Last and LastOrDefault are actually extension method from IQueryable and IEnmuerable

LINQ LastOrDefault Method Example

This is how you can use LastOrDefault method in LINQ.

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

Here is another example of LastOrDefault

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

Example of using Last method

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

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

Difference between Last and LastOrDefault

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

 
Linq lastordefault query example: last vs lastordefault in linq
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