2016-06-29 12 views
2

Hier ist meine Einheit StrukturWie Nested Sammlung innerhalb Wörterbuch mit LINQ C#

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 

Die Funktion in der Business-Schicht auf Filter Dictionary<int, List<Transaction>> zurückkehrt, welche wie diese im Grunde ist

Key   Value 
CompanyID, List<Transaction> 

Bisher habe ich nur erreicht dies

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

kann jemand bitte helfen

+1

Sie müssen im Grunde den 'Wert' addieren, wo Ihre Flagge' Positiv/Negativ' ist. –

+1

Als Randnotiz sollte es wahrscheinlich besser gewesen sein, nur ein 'Positiv'-Flag auf' True/False' gesetzt zu haben. –

Antwort

4

Sie müssen nur den Wert Feld aus der Liste zusammenzufassen:

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

'Wo (t => t.Positiv)' wird nicht kompiliert. –

+0

Ich denke, es sollte '_Transaction.GetCompanyTransactions() sein. Wählen Sie (g => neu {CompanyId = g.Key, Positive = g.Value.Select (s => s.TransactionItems.Where (t => t.Positive) .Summe (t => t.Value)), Negativ = g.Value.Select (s => s.TransactionItems.Where (t => t.Negativ) .Summe (t => t.Wert))}); ' – Bruno

+0

Ja, ich habe meine Antwort aktualisiert, um dieses Problem zu beheben. – Kinetic

1

Sie müssen die Werte auf der Positive/Negative Flag basierend auf Sum.

Es ist in zwei Schritten getan: Sie müssen Sum die inneren Elemente zuerst, dann Sum die inneren Summen.

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