Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return null if using SingleOrDefault() and searching a list of numbers for a number not in list?

Tags:

c#

linq

When querying a list of positive numbers using SingleOrDefault(), how can I return null, or a custom value like -1, when a number isn't found in the list, instead of the type's default value (0 in this case)?

like image 410
Tony_Henrich Avatar asked Oct 03 '13 17:10

Tony_Henrich


People also ask

Can ToList () return null?

If you have a Query that returns a empty set then ToList returns null. You would probably expect it to return an empty list (Count = 0), which is the case when using data providers for SQL Server.

Can Linq ToList return null?

in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;) Save this answer.

What does FirstOrDefault return if not found?

FirstOrDefault() returns the default value (null) if there is no result data and you can see the result in the following screen.


2 Answers

You can use DefaultIfEmpty to specify a custom default value for an empty collection:

var value = numbers.Where(MyFilter)
    .DefaultIfEmpty(-1) //or any other default value you want
    .Single(); //OrDefault not needed; DefaultIfEmpty ensures there is an item
like image 190
Servy Avatar answered Sep 28 '22 01:09

Servy


You could use:

var first = theIntegers
                .Cast<int?>()
                .SingleOrDefault(i => i == theValue) ?? valueIfNotFound;

This works by casting the items to a Nullable<int>, then using the null-coalescing operator to return the value you choose if null was returned (ie: not found).

Note this will throw if you have more than one matching item. If you don't want that behavior, use FirstOrDefault instead of SingleOrDefault.

like image 31
Reed Copsey Avatar answered Sep 28 '22 03:09

Reed Copsey