【问题标题】:Turning an IEnumerable of IEnumerables into a dictionary将 IEnumerable 的 IEnumerable 转换为字典
【发布时间】:2016-06-21 11:14:58
【问题描述】:

问题出在运行之后

 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 的解决方案。

【问题讨论】:

    标签: c# entity-framework linq dictionary


    【解决方案1】:

    试试这个:

    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?

    【讨论】:

    • 它报错是因为“已经添加了具有相同密钥的项目。”
    • @BenJones - 检查代码,因为我在前五分钟内更改了它。我现在得到的代码不会有这个错误。
    【解决方案2】:

    试试这个:

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

    dictionary 将是 Dictionary&lt;string, decimal&gt;。但是您需要确保不会有两个TempTotals 与相同的Type

    【讨论】:

    • 这不会在Type 上分组,因此如果有多个具有相同类型的项目,它将引发异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多