Sunday, August 20, 2017

Difference between SingleOrDefault and FirstOrDefault in C# Linq

In this tutorial we will see the difference between SingleOrDefault () and FirstOrDefault ().

SingleOrDefault():-
When you are exactly sure that there is only 1 result/record you should use SingleOrDefault(). If there is no result/record returned or there is more than 1 result/record this function will throw exception.
Example:-
string[] fruits = { "orange" };

string singleFruit = fruits.SingleOrDefault();

Console.WriteLine(singleFruit);

/*
 This code produces the following output:

 orange
*/


FirstOrDefault():- It will not throw any exception in case when there is no result/record returned from database rather it returns null when there is no result. It is slightly better in performance than SingleOrDefault()that is why it is recommended to use when you need single value from database.
Example:-

int[] integers = { };
int first = integers.FirstOrDefault();
Console.WriteLine(first);

/*
 This code produces the following output:

 0
*/

No comments:

Post a Comment