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

SingleOrDefault vs FirstOrDefault


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 grater the FirstOrDefault and SingleOrDefault on a sequence with more than one element, it throws an exception.

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

Single

It is 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 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 same as Single(), but it can handle the null value single() is not handle null value.An exception has been occured  when  more than one match 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 primary key.It  will generate a regular TSQL like "SELECT ...". SingleOrDefault is the slow perfomance compare FirstOrDefault because it needs to check if there is only one element and therefore always iterates the whole enumerable.

First

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

FirstOrDefault 

FirstOrDefault() will not throw any exception If more than one elements are satisfied the condition.It will generate query like "SELECT TOP 1 * from <table-name> WHERE Id= 1". FirstOrDefault same as First(), but not thrown 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 is some small differences between FirstOrDefault/SingleOrDefault.

Mahira  khanna

Mahira khanna

I have the skills you need for you company blog, website, or other content materials

Comments



Report Response