Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DefaultIfEmpty returning null

I am working with C#, .NET4.5, EF6(shouldn't matter really).

I am selecting some values from db then .ToList() them and then adding DefaultIfEmpty(new ActualFee{Net = 0, Vat = 0}) if one does not exist, and I get null

public static ConveyancingSummaryVm ToConveyancingSummaryVm(this Tuple<IEnumerable<ActualFee>, ConveyancingAnswer, Customer> conveyancePricingAnswersAndCustomer)
        {
            var purchaseFees = conveyancePricingAnswersAndCustomer.Item1.Where(o => o.ConveyancingSaleType == "Purchase").ToList();

            if (purchaseFees.Any())
            {
                var discount = purchaseFees.DefaultIfEmpty(new ActualFee{Net = 0, Vat = 0}).SingleOrDefault(o => o.Title.Contains("Discount")); 

                conveyancingSummaryVm.IsPurchaseFreehold = conveyancePricingAnswersAndCustomer.Item2.PropertyBoughtIsFreehold;
...

enter image description here

I must be missing something obvious here.

like image 671
Matas Vaitkevicius Avatar asked Jun 14 '26 21:06

Matas Vaitkevicius


2 Answers

There is no way for DefaultIfEmpty to return null in this case. When there is no element it returns an ActualFee instance and the Title does not contain Discount. So that's why SingleOrDefault returns null.

so you are saying that DefaultIfEmpty does not work for SingleOrDefault?

No, DefaultIfEmpty works and returns the expected value. And then SingleOrDefault runs on the return value of DefaultIfEmpty and returns null because there is no element in the sequence that satisfies your condition.

You can use null coalescing operator to get the behaviour you want:

var discount = purchaseFees.FirstOrDefault(o => o.Title.Contains("Discount")) 
              ?? new ActualFee{Net = 0, Vat = 0};
like image 181
Selman Genç Avatar answered Jun 17 '26 11:06

Selman Genç


SingleOrDefault must've returned null. If DefaultIfEmpty had returned null, it would've returned a Object reference not set to an instance of an object. Please rewrite that statement without chaining.

like image 21
JunaidKirkire Avatar answered Jun 17 '26 10:06

JunaidKirkire