gpt4 book ai didi

c# - 如何使用 LINQ C# 过滤字典中的嵌套集合

转载 作者:行者123 更新时间:2023-12-03 03:13:24 25 4
gpt4 key购买 nike

这是我的实体结构

Transaction Entity 

TransactionID, CompanyID TransactionItems
1 10 List<TransactionItems>
2 10 List<TransactionItems>
3 20 List<TransactionItems>

TransactionItems Entity

TransactionItemID TransactionID Value Postive Negative
1 2 10 yes
2 2 20 yes
3 2 30 yes
4 3 100 yes
5 3 200 yes

I need to sum the values of Value based on positive or negative flag and then compute total like this

CompanyID Postive Negative
10 30 30
20 200 100

业务层函数返回Dictionary<int, List<Transaction>>基本上是这样的

Key         Value
CompanyID, List<Transaction>

到目前为止我只实现了这个

 _Transaction.GetCompanyTransactions().
Select(_Company => new
{
Company = _Company.Key,
Positive =
Negative =
});

谁能帮忙

最佳答案

您只需对列表中的值字段求和即可:

_Transaction.GetCompanyTransactions()
.Select(g => new {
CompanyId = g.Key,
Positive = g.Value.SelectMany(t => t.TransactionItems).Where(t => t.Positive).Sum(t => t.Value),
Negative = g.Value.SelectMany(t => t.TransactionItems).Where(t => t.Negative).Sum(t => t.Value)})
});

关于c# - 如何使用 LINQ C# 过滤字典中的嵌套集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38106325/

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