簡體   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