我如何 return 使用 Linq 按日期和 ID 分组的金额总和

How can I return an amount sum grouped by date and ID using Linq

我想要 return 类型对象中的数据 IQueryable<Money>,并且数据库中的钱 table 保留了钱交易记录 (buy/sell)每次发生买卖时,都会有几个客户保存日期和金额,我使用存储库获取此数据,如下所示:

ID                 Value        Action         Date 
1                  12             Buy          1/2/2018
1                  -5             Sell         1/2/2018 
1                  7              Buy          1/2/2018 
1                  3              Buy          1/2/2018

2                  35             Buy          1/2/2018
2                  -27            Sell         1/2/2018 
2                  20             Buy          1/2/2018 

4                  20              Buy         1/2/2018
4                  30              Buy         1/2/2018
4                  -50             Sell        1/2/2018 

1                  15              Buy         12/10/2017
1                  -23             Sell        12/10/2017 
1                  20              Buy         30/10/2017 
1                  3               Buy         30/10/2017

在我的 C# 代码中,我想使用 LINQ 和 EF 显示每个客户每天的总买卖金额(按日期和客户 ID 求和(买)求和(卖)组),并将值显示在一个网格,如下:

ID                Buy Value       Sell Value         Date 
1                  22                 -5              1/2/2018
1                  15                 -23             12/10/2017
1                  23                  -              30/10/2017
2                  55                 -27             1/2/2018 
4                  50                 -50             1/2/2018 

我不确定这是否可以通过代码完成,或者最好为它创建一个视图。

到目前为止我尝试过的:

public List<Money> GetData(MoneyFilter filter)
{
    var data = _moneyRepository.GetFiltered(filter);

    List<MoneyDto> list = new List<MoneyDto>();

    foreach (var item in data.GroupBy(x => new {x.Date,x.ContactId}))
    {
        list.Add(new MoneyInOutFlowDto
        {
            Sell = item.Sum(x => x.Amount<0?x.Amount:0),
            Buy = item.Sum(x => x.Amount>0?x.Amount:0),
            Id = item.ContactId,
            Date = item.Date
        });
    }
    return list;
}

public class MoneyDto 
{
    public int ContactId {get;set;}
    public decimal Sell {get;set;}
    public decimal Buy {get;set;}
    public DateTime Date {get;set;}        
}
var data = _moneyRepository.GetFiltered(filter);

data.GroupBy(x => new { x.Action, x.Id }).Sum(x => x.Value).Select(x => new MoneyDto{
//Here assign the values
Id = .xId //and the other values
}).ToList();

您通过分组开始得很好,但选择实施不正确

var data = _moneyRepository.GetFiltered(filter);

List<MoneyDto> list = data.GroupBy(_ => new { _.Date, _.ContactId })
    .Select(g => new MoneyDto {
        ContactId = g.Key.ContactId,
        Date = g.Key.Date,
        Sell = g.Where(_ => _.Action == "Sell").Sum(_ => _.Amount),
        Buy = g.Where(_ => _.Action == "Buy").Sum(_ => _.Amount),
    }).ToList();