gpt4 book ai didi

具有复杂结果的 c# Linq

转载 作者:行者123 更新时间:2023-11-30 20:41:39 25 4
gpt4 key购买 nike

我有以下类(class):

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。

最佳答案

编辑:更新了多个组 key 。

我可以这样做。

输出:

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

结果:

enter image description here

输入:

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

关于具有复杂结果的 c# Linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32179756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com