【问题标题】:c# Linq with complex resultc# Linq 结果复杂
【发布时间】:2015-08-24 10:13:05
【问题描述】:

我有以下课程:

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

使用以下数据(为澄清而简化/排序):

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 reduce。

【问题讨论】:

  • 我猜应该是10/01/2015 而不是2014 是吗..?否则 10/01/2014 也小于 12/02/2014
  • 可能值得明确说明您也按AccountId 分组。至少我是这么认为的,因为一切都小于或等于23/11/2014,并且只有在您也限制在AccountId 之内时,您的数学才有意义。
  • 为什么 12/02/2014 只有 200 个总量? 10/01/2014 少于 12/02/2014
  • @Chris,我认为结果很明显。我的错。已编辑。感谢您指出。

标签: c# linq mapreduce group-by ravendb


【解决方案1】:

编辑:使用多个组键更新。

我可以这样做。

输出:

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
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    相关资源
    最近更新 更多