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
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.
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.