具有复杂结果的 c# Linq

c# Linq with complex result

我有以下 class:

class Voucher
{
    string AccountId { get; set; }
    Date Date { get; set; } // This class only implements the date part
    decimal Amount { get; set; }
}

使用以下数据(simplified/sorted 进行说明):

1 12/02/2014 100
1 12/02/2014 100
1 23/11/2014 100
1 23/11/2014 100
2 10/01/2014 100
2 10/01/2014 100
2 09/08/2014 100

我希望结果按帐户和日期分组,但金额应为小于日期键的所有条目的总和:

1 12/02/2014 200
1 23/11/2014 400
2 10/01/2014 200
2 09/08/2014 300

我想不出可以做到这一点的解决方案。以日期作为键进行分组将给我该特定日期的总金额,我不需要。这能做到吗?

此外,我需要在一个查询中完成此操作,因为我将使用此查询来减少 RavenDB。

编辑:更新了多个组密钥。

我可以这样做。

输出:

var result = from i in input
             group i by new { i.Date.Date, i.AccountId }
             into grouped
             select new {
                 accountId = grouped.Key.AccountId,
                 date = grouped.Key.Date,
                 total = (from kv in input
                          where kv.Date.Date <= grouped.Key.Date && kv.AccountId == grouped.Key.AccountId
                          select kv).Sum(i => i.Amount)
             };

结果:

输入:

var input = new[] {
    new Vocuher() {
        AccountId = "1",
        Date = DateTime.Parse("12/02/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "1",
        Date = DateTime.Parse("12/02/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "1",
        Date = DateTime.Parse("23/11/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "1",
        Date = DateTime.Parse("23/11/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "2",
        Date = DateTime.Parse("10/01/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "2",
        Date = DateTime.Parse("10/01/2014"),
        Amount = 100
    },
    new Vocuher() {
        AccountId = "2",
        Date = DateTime.Parse("09/08/2014"),
        Amount = 100
    }
};