In Linq, what's the difference between .FirstOrDefault and .SingleOrDefault

I do not know the difference between FirstOrDefault and SingleOrDefault . When should you use the first and when should you use the second?

+7
source share
3 answers

FirstOrDefault() for those cases where it is expected that the input collection will contain zero or more results, and the call returns the first element, if there are several results, by default, if not.

SingleOrDefault() for those cases in which the input collection expects zero or one result, and the call returns one result if only one result is present, by default, if there are no results and exceptions, if there is more than one result.

+14
source

SingleOrDefault throws a "Sequence contains more than one element" exception if more than one element exists.

+7
source

firstordefault will occupy several lines, but just return one of them first, if it is null it can handle an exception At first it will take several lines, but just return the first of them, if it is null this will throw an exception singleordefault will occupy only one line, but will be returned , it can handle exceptions, if it is zero single it will take only one line, but will return it and will not be able to handle exceptions

If your result set returns 0 records:

SingleOrDefault returns the default value for the type (for example, the default value for int is 0) FirstOrDefault returns the default value for the type. As a result, the result returns 1 record:

SingleOrDefault returns this record FirstOrDefault returns this record If your result set returns many records:

SingleOrDefault throws an exception. FirstOrDefault returns the first record. Output:

If you want to throw an exception if the result set contains many records, use SingleOrDefault.

If you always want 1 record, no matter what the result set contains, use FirstOrDefault

0
source

All Articles