简体   繁体   English

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

[英]How to Filter Nested Collection within Dictionary using LINQ C#

Here is my entity structure 这是我的实体结构

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

The function in Business layer is returning Dictionary<int, List<Transaction>> which is basically like this 业务层中的函数返回的Dictionary<int, List<Transaction>>基本上是这样的

Key         Value
CompanyID, List<Transaction>

So far i have only achieved this 到目前为止,我只实现了这一点

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

can any one help please 有人可以帮忙吗

You just have to sum the value field from the list : 您只需要对列表中的value字段求和:

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

You need to Sum the values based on the Positive/Negative flag. 您需要根据Positive/Negative标记Sum

It is done in two steps: you need to Sum the inner items first, then Sum the inner sums. 这两个步骤完成:你需要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)),
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM