Click here to Skip to main content
16,004,782 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Between SingleOrdefault() and FirstOrdefault()

What I have tried:

Difference between FirstorDefault() and SingleOrDefault() in C#?
Posted
Updated 16-Aug-18 23:08pm

First or default will return the type default if nothing is in the list, and the first item if there are one or more items.

Single or default will return the type default if nothing is in the list, the only item in the list if there is only one item, and will throw an exception if there is more than one item in the list.

So the difference is that FirstOrDefault ignores when there is more than one item, SingleOrDefault throws an exception if there is more than one item.
 
Share this answer
 
Ignoring the fact that the "What I have tried" section doesn't say that you actually tried anything, this is a fairly interesting question to answer. Let's get the similarities between the two methods out of the way first:

They both return one value.
That value will be the value found unless there is no match, in which case the default value will be returned.
The default value will either be null (for nullable types) or the default for a non-nullable type.

Given that set of abilities, why do they differ?

First returns the first matching element. In other words, it stops scanning the list AS SOON AS IT FINDS A MATCH.
Single returns the matching element ONLY if there is one element. In other words, it continues scanning to make sure there's only one matching element.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900