2016-06-21 20 views
5

的問題是運行談到IEnumerables的IEnumerable成字典

reportData = dbContext.FinancialsBySupplierAuditPeriodStatusType 
         .Where(v => v.ReviewPeriodID == reportFilter.ReviewPeriodID && v.StatusCategoryID == reportFilter.StatusCategoryID) 
         .GroupBy(s => new { s.SupplierID }) 

         .Select(g => new DrilldownReportItem { 
          SupplierID = g.Key.SupplierID, 
          SupplierName = g.Max(v => v.SupplierName), 
          AccountNo = g.Max(v => v.AccountNo), 
          TempTotals = g.Select(v => new TempTotals { ClaimType = v.TypeDesc ?? "Old Claims", Amount = v.Amount }) 
         }).OrderBy(r => r.SupplierName).ToList(); 

溫度總計之後是包含一個簡單類的

public class TempTotals { 
    public string Type { get; set; } 
    public decimal? Amount { get; set; } 
} 

的想法是再取一的IEnumerable一個IEnumerable這個數據並將它分組到一個字典中,這樣我就可以得到所有金額與鍵類型的總和。

最終的結果應該是這樣的:

Dictionary<string, decimal> test = new Dictionary<string, decimal>() { 
       {"Claim",2 }, 
       {"Query", 500 }, 
       {"Normal", 700 } 
      }; 

我知道,我可能只是它的foreach但是我正在尋找使用LINQ的解決方案。

回答

7

嘗試這種情況:

Dictionary<string, decimal?> test = 
    reportData 
     .SelectMany(rd => rd.TempTotals) 
     .GroupBy(tt => tt.ClaimType, tt => tt.Amount) 
     .ToDictionary(g => g.Key, g => g.Sum()); 

由於Amount類型是decimal?然後字典值也是decimal?

+0

它抱怨,因爲「一個項目具有相同的密鑰已被添加。」 –

+0

@BenJones - 檢查代碼,因爲我在前五分鐘更改了代碼。我現在得到的代碼不能有這個錯誤。 – Enigmativity

+0

是的,這是行得通的謝謝:) –

1

試試這個:

IEnumerable<IEnumerable<TempTotals>> yourCollection; 

var dictionary = yourCollection.SelectMany(s => s).ToDictionary(k => k.Type, v => v.Amount); 

dictionaryDictionary<string, decimal>。但是你需要確保你不會有兩個TempTotalsType相同。

+0

這不會對'Type'進行分組,所以如果有多個具有相同類型的項目,它會拋出一個異常。 – juharr