如何使用LINQ C#在Dictionary中过滤嵌套集合

时间:2016-06-29 17:23:54

标签: c# linq

这是我的实体结构

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

Business层中的函数返回Dictionary<int, List<Transaction>>,基本上就像这样

Key         Value
CompanyID, List<Transaction>

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

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

任何人都可以帮助

2 个答案:

答案 0 :(得分:4)

您只需要从列表中总结值字段:

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

答案 1 :(得分:1)

您需要Sum基于Positive/Negative标记的值。

分两步完成:首先需要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)),
            });