Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SingleOrDefault: How to change the default values?

Tags:

linq

SingleOrDefault returns null, but what if I want to assign values to represent the object that wasn't found?

like image 536
zsharp Avatar asked May 04 '09 02:05

zsharp


People also ask

What is the default value of SingleOrDefault?

The default value for reference and nullable types is null . The SingleOrDefault method does not provide a way to specify a default value. If you want to specify a default value other than default(TSource) , use the DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) method as described in the Example section.

How do you use single or default?

When you want an exception to be thrown if the result set contains many records, use Single or SingleOrDefault. When you want a default value is returned if the result set contains no record, use SingleOrDefault. When you always want one record no matter what the result set contains, use First or FirstOrDefault.

What is the difference between FirstOrDefault and SingleOrDefault?

SingleOrDefault() – Same as Single(), but it can handle the null value. First() - There is at least one result, an exception is thrown if no result is returned. FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.

Does single or default return null?

SingleOrDefault() will return null (or default of the type) if nothing exists but will throw exception if you have more than one match.


2 Answers

you can do something like

myStrings.DefaultIfEmpty("myDefaultString").Single()

check out here

like image 184
oscarkuo Avatar answered Oct 16 '22 19:10

oscarkuo


?? operator. If the left argument is null, evaluate and return the second argument.

myCollection.SingleOrDefault() ?? new[]{new Item(...)}

This will only work with reference types (or nullables), but it would do what you're looking for very simply.

like image 35
Joe White Avatar answered Oct 16 '22 18:10

Joe White