如何使用linqc#在字典中过滤嵌套集合
本文关键字:过滤 嵌套 集合 字典 何使用 linqc# | 更新日期: 2023-09-27 17:53:05
这是我的实体结构
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)})
});
需要根据Positive/Negative
标志对值进行Sum
。
它分两步完成:首先需要Sum
内部项,然后Sum
内部和。
_Transaction.GetCompanyTransactions()
.Select(g => new
{
Company = g.Key,
Positive = g.Value.Sum(t => t.TransactionItems.Where(x => x.Positive).Sum(x => x.Value)),
Negative = g.Value.Sum(t => t.TransactionItems.Where(x => x.Negative).Sum(x => x.Value)),
});