c# - 将 IEnumerables 的 IEnumerable 转换为字典

标签 c# entity-framework linq dictionary

问题出在运行之后

 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();

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

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

我的想法是获取这些数据并将其分组到一个字典中,这样我就可以得到所有金额的总和,键是类型。

最终结果应该是这样的:

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

我知道我可以直接使用它,但是我正在寻找使用 LINQ 的解决方案。

最佳答案

试试这个:

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?

关于c# - 将 IEnumerables 的 IEnumerable 转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37942911/

相关文章:

wpf - EF Code First 绑定(bind)到列表框

c# - 返回一组中的前 x 项

c# - 避免单声道中未安装 PCL 引用程序集错误

c# - Android 在间隔后更新谷歌地图

c# - Linq 如何计算行数?

c# - 如何使用 c# .net 核心 Entity Framework 执行连接

c# - 将日期与字符串 Entity Framework 进行比较

c# - sql linq之间有什么区别吗

c# - 如何维护LINQ延迟执行?

c# - 使用 LINQ 返回匹配条件的数组索引的简洁方法