find and solve || findandsolve.com
Please wait.....

SingleOrDefault() Vs. FirstOrDefault() in LINQ Query

SingleOrDefault use query should result in at most a single result.FirstOrDefault is used, the query can return any amount of results but you state that you only want the first one. SingleOrDefault is fast greater than the FirstOrDefault and SingleOrDefault on a sequence with more than one element, it throws an exception.

FirstOrDefault is pointing to "At least" one item matching the query or default and SingleOrDefault is "At most"  there is one item matching the query or default.

SingleOrDefault and FirstOrDefault are LINQ extension methods used in C#. Both are used to retrieve a single element from a collection. The difference is:

So, use SingleOrDefault when you expect only one element in the collection and use FirstOrDefault when you want to retrieve the first element, but it's okay if multiple elements are present.


Single

It returns a single specific element from a collection of elements. There is exactly 1 result, an exception is thrown if none or more than one match is found for that element in the collection.

List<int> items = new List<int>() {10,20,30,40,50};
//Throw the exception if there is no element found
int result = items.Where(item => item == 10).Single();

SingleOrDefault

It is the same as Single(), but it can handle the null value single() is not handle the null value. An exception has occurred when more than one match is found for that element in the collection.

List<int> items = new List<int>() {10,20,30,40,50};
//Throw the exception after satisfied the condition more than one elements
int result = items.Where(item => item == 10).SingleOrDefault();

SingleOrDefault  is the best for use if querying for data that is guaranteed to be unique like as a primary key.It will generate a regular TSQL like "SELECT ...". SingleOrDefault is the slow performance compared FirstOrDefault because it needs to check if there is only one element and therefore always iterates the whole enumerable.

First

It returns the first specific element from a collection of the element if there are one or more records than one match found for that element. The First() method will always generate the TSQL statement like as "SELECT TOP 1 FROM ...." and simply gives you the first one.

FirstOrDefault 

FirstOrDefault() will not throw any exception If more than one element is satisfied the condition. It will generate queries like SQL "SELECT TOP 1 * from <table-name> WHERE Id= 1". FirstOrDefault same as First(), but not throw any exception or return null when there is no result.

List<int> items = new List<int>() {10,20,30,40,50};
//Throw the no exception after satisfied the condition more than one elements.
int result = items.Where(item => item == 10).FirstOrDefault ();


In the case of Fist()  / FirstOrDefault(), only one row has been retrieved from the database or list of data so it performs slightly better than single / SingleOrDefault.There are some small differences between FirstOrDefault/SingleOrDefault.


SingleOrDefault vs FirstOrDefault with example

SingleOrDefault and FirstOrDefault are LINQ extension methods in C# used to retrieve a single element from a collection. Here's an example to demonstrate the difference between them:


List<int> numbers = new List<int> { 1, 2, 3 }; // Using SingleOrDefault int singleNumber = numbers.SingleOrDefault(n => n == 2); Console.WriteLine(singleNumber); // Output: 2 // Throws an exception if more than one element is found try { int multipleNumbers = numbers.SingleOrDefault(n => n > 1); Console.WriteLine(multipleNumbers); } catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); // Output: The input sequence contains more than one element. } // Using FirstOrDefault int firstNumber = numbers.FirstOrDefault(n => n > 1); Console.WriteLine(firstNumber); // Output: 2

In this example, we have a list of numbers { 1, 2, 3 }. We use SingleOrDefault to retrieve the number 2 from the list, and it works as expected because only one element 2 matches the condition n == 2. However, if we try to retrieve all numbers greater than 1, there are multiple elements that match the condition, so an exception is thrown.

On the other hand, if we use FirstOrDefault, it returns the first element that matches the condition n > 1, which is 2. It doesn't throw an exception even though multiple elements match the condition.

Related information

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

If findandsolve.com felt valuable to you, feel free to share it.

Comments



Report Response