Ads

C# Programming 24 - When to use First() and when to use FirstOrDefault() in LINQ


Hello All,


In this article we will leran about First() and FirstOrDefault() method in LINQ.


LINQ stands for Language-Integrated Query. It is a set of technologies that enable you to query and manipulate data from various sources using C# syntax. With LINQ, you can write queries that are checked at compile time, supported by IntelliSense, and integrated with object-oriented programming.


LINQ queries can be written in two ways: query syntax and method syntax. Query syntax is similar to SQL and uses keywords such as from, where, select, and group. Method syntax uses extension methods and lambda expressions to perform the same operations.

Lets discuss about  First() and FirstOrDefault()


First()


  • Always it Returns first element of a sequence.
  • It throw an error when There is no element in the result or source is null.
  • you should use it,If more than one element is expected and you want only first element.


    var result = dc.Employee.First(x => x.EmpId == 1);


There is only one record where EmpId = 1. Should return this record


    var result = dc.Employee.First(x => x.FullName == "Sam");


There are multiple records where FullName == "Sam". First record should be return.


    var result = dc.Employee.First(x => x.EmpId ==000000);


There is no record with EmpId == 000000. An error should be occur.

InvalidOperationException: Sequence contains no elements


FirstOrDefault():

  • Returns first element of a sequence, or a default value if no element is found.
  • It throws an error Only if the source is null.
  • you should use it, If more than one element is expected and you want only first element. Also good if result is empty.



    var result = dc.Employee.FirstOrDefault(x => x.EmpId == 1);



There is only one record where EmpId == 1. Should return this record



    var result = dc.Employee.FirstOrDefault(x => x.FullName == "Sam");



There are multiple records where FullName == "Sam". First record should be return.


    var result = dc.Employee.FirstOrDefault(x => x.EmpId ==0000);


There is no record with EmpId == 0000. The return value is null

Finally, So If you willing to handle a possible exception, then .First() is fine. If you prefer to check the return value for != null anyway, then .FirstOrDefault() is your better choice.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !