简体   繁体   中英

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

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

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);

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.

You're looking for DefaultIfEmpty .

var itemCounts = from i in data.collection
                 where i.Type == type
                 select i.Count;

var itemCountsOrMinusOne = itemCounts.DefaultIfEmpty(-1);

The first will give you the item counts, or an IEnumerable that returns no elements.

The second will then give you the item counts, or an IEnuemrable that just returns -1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM