Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for linq select item if query didn't return anything

Tags:

c#

linq

How to insert a default value to the returned collection if the where condition returns no results?

from i in data.collection
where i.Type == type
select i.Count
like image 891
kul_mi Avatar asked Nov 27 '12 12:11

kul_mi


People also ask

What does LINQ return when the results are empty?

It will return an empty enumerable.

What does FirstOrDefault return if not found?

The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() returns a default value (null) if there is no result data.

What does select in LINQ return?

LINQ Select operator is used to return an IEnumerable collection of items, including the data performed on the transformation of the method. By using Select Operator, we can shape the data as per our needs.

What is default value LINQ?

The default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value.


2 Answers

Use the Enumerable.DefaultIfEmpty method to do this.

Example (in method syntax because it IMHO is less awkward):

data.collection.Where(i => i.Type == type)
               .DefaultIfEmpty(defaultObject)
               .Select(i => i.Count);
like image 199
Jon Avatar answered Oct 29 '22 00:10

Jon


There's DefaultIfEmpty() method.

In the method syntax, you can use it like this:

data.Collection
    .Where(i => i.Type == type)
    .DefaultIfEmpty(yourDefaultValue)
    .Select(i => i.Count);

If the Where filter returns no items, a one-item enumerable with yourDefaultValue is used as an input for the Select projection.

like image 32
Honza Brestan Avatar answered Oct 28 '22 23:10

Honza Brestan