对集合进行分组并返回字典

jam*_*wis 17 .net c# linq refactoring

我写了一个方法,它收集了一些项目(价格项 - 每个项目都有一个数量和一个代码),然后按代码对它们进行分组,然后返回一个IDictionary,其中键是项目的代码,值是组带有该代码的项目(希望有意义!)

这是方法的实现:

public IDictionary<string, IEnumerable<PriceDetail>> GetGroupedPriceDetails(IEnumerable<PriceDetail> priceDetails)
{
    // create a dictionary to return
    var groupedPriceDetails = new Dictionary<string, IEnumerable<PriceDetail>>();

    // group the price details by code
    var grouping = priceDetails.GroupBy(priceDetail => priceDetail.Code);

    // foreach grouping, add the code as key and collection as value to the dictionary
    foreach (var group in grouping)
    {
        groupedPriceDetails.Add(group.Key, group);
    }

    // return the collection
    return groupedPriceDetails;
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试重构这个使用ToDictionary,如下所示:

// group the price details by code and return
return priceDetails.GroupBy(priceDetail => priceDetail.Code)
                   .ToDictionary(group => group.Key, group => group);
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,我收到一个错误,说我无法将字典转换string, IGrouping<string, PriceDetail>成字典string, IEnumerable<PriceDetail>.

谁能告诉我如何正确地重构我对这种方法的第一次尝试?我觉得有一种更简洁的写作方式,但无法弄清楚!

bob*_*wah 36

你不能这样做:

priceDetails.GroupBy(priceDetail => priceDetail.Code)
               .ToDictionary(group => group.Key, group => group.ToList())
Run Code Online (Sandbox Code Playgroud)

  • 我觉得这就是答案 (6认同)
  • 这就是我一直在寻找的 (2认同)

Jak*_*cki 15

怎么样:

public ILookup<string, PriceDetail> GetGroupedPriceDetails(IEnumerable<PriceDetail> priceDetails)
{
     return priceDetails.ToLookup(priceDetail => priceDetail.Code);
}
Run Code Online (Sandbox Code Playgroud)