DoIt
DoIt

Reputation: 3438

Returning 0 when count is applied in empty list using LINQ

I am working on a list to get count after applying a filter like below

ValueRaw = pCounts.Count() > 0 ? pCounts.SingleOrDefault(x => x.IsNew)?.Count : 0 

above line returns null when pCounts.SingleOrDefault(x => x.IsNew) is empty

How do I change it to return 0 instead of null

Upvotes: 0

Views: 5079

Answers (2)

MetaColon
MetaColon

Reputation: 2871

You can do it like this (you don't need your first check):

ValueRaw = pCounts.SingleOrDefault(x => x.IsNew)?.Count ?? 0;

This uses the null coalising operator (see here). It takes the value left of it if it isn't null and otherwise the value right of it.

However, you could of course still write it with a conditional mark:

var temp = pCounts.SingleOrDefault(x => x.IsNew)?.Count;
ValueRaw = temp == null ? 0 : temp;

Or even longer with an if:

var temp = pCounts.SingleOrDefault(x => x.IsNew)?.Count;
if(temp == null)
    ValueRaw = 0;
else
    ValueRaw = temp;

Upvotes: 7

JSQuareD
JSQuareD

Reputation: 4776

First, the Count() check is not necessary. SingleOrDefault will return default (null) when the collection is empty. So your original expression can be simplified to:

ValueRaw = pCounts.SingleOrDefault(x => x.IsNew)?.Count;

If you want ValueRaw to be 0 when no element satisfies the condition, you can use the null-coalescing operator:

ValueRaw = pCounts.SingleOrDefault(x => x.IsNew)?.Count ?? 0;

This will give you the Count of the first element that satisfies the condition, or 0 if there is no such element. In particular, the elements in your collection must themselves be collections (otherwise you cannot apply Count to it). Perhaps you actually intend to use Where:

ValueRaw = pCounts.Where(x => x.IsNew).Count();

This will give you the number of elements that satisfy the condition.

Upvotes: 3

Related Questions