简体   繁体   中英

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

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 :

_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.

It is done in two steps: you need to Sum the inner items first, then Sum the inner sums.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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