.Sum()函数返回错误结果

时间:2018-07-18 02:50:29

标签: c# linq

数据库中的数据为:

table Bill      
ActualAmount    PaidAmount
150              (null)
150              (null)
2400              400

当我执行代码时:

var bills = _dbContext.Bills.Where(x => x.Customer.Id == customer.Id);
var amount = bills.Sum(x => (x.ActualAmount - x.PaidAmount??0));

返回2000。

如果我执行:

var amount = bills.Sum(x => (x.ActualAmount))- bills.Sum(x => (x.PaidAmount));

它返回2300(我想要这个结果)。

任何人都可以告诉原因吗?

1 个答案:

答案 0 :(得分:4)

如果在(x.PaidAmount ?? 0)周围加上括号,则优先于减法。但是,您得到的结果是700,而不是2300。

更新

将第三条记录的PaidAmount更改为400,导致总和为2300。还更新了小提琴演示。

类似的东西:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<Bill> bills = new List<Bill>();
        bills.Add(new Bill() {ActualAmount = 150, PaidAmount = null});
        bills.Add(new Bill() {ActualAmount = 150, PaidAmount = null});
        // bills.Add(new Bill() {ActualAmount = 2400, PaidAmount = 2000});
        bills.Add(new Bill() {ActualAmount = 2400, PaidAmount = 400});

        var amount = bills.Sum(x => (x.ActualAmount - (x.PaidAmount ?? 0)));
        Console.WriteLine(amount);
    }
}

public class Bill
{
    public double? ActualAmount {get; set;}
    public double? PaidAmount {get; set;}
}

结果

2300

Fiddle Demo