Single, SingleOrDefault() vs First, FirstOrDefault() in C#

The distinctions between Single, SingleOrDefault, and First, FirstOrDefault in C# are described in this article, along with information on when to use them. Their explanations will help us choose what should be included in our code to make our task simpler. You will get the full concept of these characteristics at the end of this article.


FIRST ( )method in C#:


In the case of First, If one or more matches are found for a given element, it returns the first specified element from the collection of items. An exception is raised if there isn't a match for that element in the collection. It returns the first element of a collection or the first element that satisfies a condition.

Given below is an example of First.

IList<intintList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };

IList<stringstrList = new List<string>() { null, "Two", "Three", "Four", "Five" };

IList<stringemptyList = new List<string>();


Console.WriteLine("1st Element in intList: {0}", intList.First());

Console.WriteLine("1st Even Element in intList: {0}", intList.First(i=>i % 2 == 0));


Console.WriteLine("1st Element in strList: {0}", strList.First());


Console.WriteLine(emptyList.First());

Console.WriteLine("emptyList.First() throws an InvalidOperationException");

Console.WriteLine("-------------------------------------------------------------");





Output:



1st Element in intList: 7

1stEven ElementinintList: 10

1stElementinstrList:

emptyList.First()throwsanInvalidOperationException

-------------------------------------------------------------

Run-timeexception: Sequencecontainsnoelements...




FirstOrDefault ( ) in C#:


In the case of FirstOrDefault, If one or more matches are found for a given element, it returns the first specified element from the collection of items. If there isn't a match for that element in the collection, a default value is returned. It returns the first element of a collection or the first element that satisfies a condition. Returns a default value if the index is out of range.

Given below is an example of firstordefault().


 

 IList<intintList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };

 IList<stringstrList = new List<string>() { null, "Two", "Three", "Four", "Five" };


 Console.WriteLine("1st Element in intList: {0}", intList.FirstOrDefault());

 Console.WriteLine("1st Even Element in intList: {0}", intList.FirstOrDefault (i=>i % 2 == 0));


 Console.WriteLine("1st Element in strList: {0}", strList. FirstOrDefault ());




Output:


 1st Element in intList: 7

 1st Even Element in intList: 10

 1st Element in strList:




Single ( ) method in C#:


In the case of single, If an element match is discovered, it returns a single particular element from a group of elements. An exception is raised if there are zero or more matches for that element in the collection. It returns the only element from a collection or the only element that satisfies a condition. If Single() finds no elements or more than one element in the collection then throws InvalidOperationException.

Given below is an example of Single.

 

 IList<intoneElementList = new List<int>() { 7 };

 IList<intintList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };


 Console.WriteLine("The only element in oneElementList: {0}", oneElementList.Single());

 Console.WriteLine("The only element which is less than 10 in intList: {0}"

 intList.Single(i=>i<10));



Output:

 

 The only element in oneElementList: 7

 The only element which is less than 10 in intList: 7




SingleOrDefault ( ) in C#:


In the case of SingleOrDefault, If an element match is discovered, it returns a single particular element from a group of elements. If there are multiple matches for that element in the collection, an exception is raised. If there isn't a match for that element in the collection, a default value is returned. The same as Single, except that it returns a default value of a specified generic type, instead of throwing an exception if no element is found for the specified condition. However, it will throw InvalidOperationException if it found more than one element for the specified condition in the collection.


Given below is an example of singleordefault.

 

 IList<intoneElementList = new List<int>() { 7 };

 IList<intintList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };

 IList<stringemptyList = new List<string>();


 Console.WriteLine("The only element in oneElementList: {0}",

             oneElementList.SingleOrDefault());

 Console.WriteLine("Element in emptyList: {0}", emptyList.SingleOrDefault());



Output:

 

 The only element in oneElementList: 7

 Element i nemptyList: 0





Difference between SingleOrDefault and FirstOrDefault:




  • In the case of SingleOrDefault it returns a single,  specific element of a sequence, or a default value if that element is not found. Whereas  FirstOrDefault returns the first element of a sequence, or a default value if no element is found.


  • SingleOrDefault is the same as Single(), but it can handle the null value. Whereas, FirstOrDefault is the same as First(), but does not throw any exception or return null when there is no result.


  • Use SingleOrDefault when you want a default value to be returned if there are no records in the result set. Whereas, Use FirstOrDefault to get a default value if the result set has no records.


  •  We use SingleOrDefault When 0 or 1 elements are expected. Whereas, We use FirstOrDeafult when more than 1 element is expected and you want only the first. Also, it is fine for the result to be empty.


  • In the case of SingleOrDefault it returns a single specific element from a collection of elements if an element match is found. An exception is thrown if more than one match is found for that element in the collection. A default value is returned, if no match is found for that element in the collection.


  • In the case of FirstOrDefault it returns the first specific element from a collection of elements if one or more than one match is found for that element. A default value is returned, if no match is found for that element in the collection.


  • FirstOrDefault usually performs faster as compared SingleOrDefault, since these iterate the collection until they find the first match. While SingleOrDefault iterates the whole collection to find one single match.


Conclusion:


The First method will produce an exception if the data source is empty or if the given condition returns no data, whereas the FirstOrDefault method will not throw an exception and instead will provide a default value based on the data type of the element. The Single method will throw an exception while the SingleOrDefault method will not throw an exception instead it returns a default value.

I hope you found this post to be interesting and helpful. Please add your opinions and suggestions to the discussion below.




Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee