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
It will return an empty enumerable.
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.
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.
The default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With