繁体   English   中英

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

[英]Group a collection and return a Dictionary

我编写了一个方法,它采用一组项目(价格项目 - 每个项目都有一个数量和一个代码)并按代码对它们进行分组,然后返回一个 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;
}

然后我尝试重构它以使用 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, IGrouping<string, PriceDetail>转换为string, IEnumerable<PriceDetail>字典string, IEnumerable<PriceDetail>

有人能告诉我如何正确重构我对这种方法的第一次尝试吗? 感觉有更简洁的写法但是想不通!

你不能这样做:

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

怎么样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM