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

时间:2012-02-08 15:56:38

标签: c# .net linq refactoring

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

以下是该方法的实现:

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;
}

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

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

我尝试编译时遇到错误,说我无法将string, IGrouping<string, PriceDetail>字典转换为string, IEnumerable<PriceDetail>字典。

有人能告诉我如何正确重构我对此方法的第一次尝试吗?我觉得有一种更简洁的写作方式,但无法弄明白!

2 个答案:

答案 0 :(得分:29)

你不能这样做:

priceDetails.GroupBy(priceDetail => priceDetail.Code)
               .ToDictionary(group => group.Key, group => group.ToList())

答案 1 :(得分:14)

怎么样:

public ILookup<string, PriceDetail> GetGroupedPriceDetails(IEnumerable<PriceDetail> priceDetails)
{
     return priceDetails.ToLookup(priceDetail => priceDetail.Code);
}
相关问题