Sami
Sami

Reputation: 125

DefaultIfEmpty is ignored

I am trying to figure out why this LINQ query (C#) doesn't work as expected:

// If the user receives 3 salaries, take the first, if not, show as 100 
var salary = populationData
             .Select(
                 x => x.AdultData?
                       .TaxPayerData?
                       .Where(x => x.Salary.Count == 3)
                       .Select(x => x.Value).FirstOrDefault()
             )
             .DefaultIfEmpty(100)
             .ToList();

PS I corrected the names of the properties, they were misleading, sorry.

Suppose for some people IsAdult = false and TaxPayer = null, for those people I need DefaultIfEmpty = 100, or any other value I choose, but not null. Currently, my result comes as null. Any thoughts, please?

Upvotes: 0

Views: 163

Answers (1)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14228

You can try this way

// If the user receives 3 salaries, take the first, if not, show as 100 
var salary = populationData
             .Select(
                 x => {
                       var result = x.AdultData?
                       .TaxPayerData?
                       .Where(x => x.Salary.Count == 3)
                       .Select(x => x.Value).FirstOrDefault()
                       return result ?? 100;}
             )
             .ToList();

Upvotes: 1

Related Questions