我正在使用 C#
、.NET4.5
、EF6
(实际上应该不重要)。
我从数据库中选择一些值,然后.ToList()
它们,然后添加DefaultIfEmpty(new ActualFee{Net = 0, Vat = 0})
(如果有人这样做)不存在,我得到 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;
...
我一定在这里遗漏了一些明显的东西。
最佳答案
在这种情况下,DefaultIfEmpty
无法返回 null。当没有元素时,它返回一个 ActualFee
实例,并且 Title
不包含 Discount
。这就是 SingleOrDefault
返回 null
的原因。
so you are saying that DefaultIfEmpty does not work for SingleOrDefault?
不,DefaultIfEmpty
有效并返回预期值。然后 SingleOrDefault
在 DefaultIfEmpty
的返回值上运行并返回 null,因为序列中没有满足您的条件的元素。
您可以使用空合并运算符来获得您想要的行为:
var discount = purchaseFees.FirstOrDefault(o => o.Title.Contains("Discount"))
?? new ActualFee{Net = 0, Vat = 0};
关于c# - DefaultIfEmpty 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28298087/