将IEnumerable的IEnumerable转换为字典

Ben*_*nes 5 c# linq dictionary entity-framework

问题是在跑完之后

 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();
Run Code Online (Sandbox Code Playgroud)

Temp totals是一个IEnumerable,它包含一个简单类的IEnumerable

public class TempTotals {
    public string Type { get; set; }
    public decimal? Amount { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我们的想法是获取这些数据并将其分组到一个字典中,以便我可以获得所有金额的总和,其中密钥是类型.

最终结果应如下所示:

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

我知道我可以预先知道它,但我正在寻找使用LINQ的解决方案.

Eni*_*ity 7

试试这个:

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

既然类型Amountdecimal?字典值也是decimal?.