简体   繁体   中英

Group a collection and return a Dictionary

I've written a method that takes a collection of items (price items - each item has an amount and a code) and groups them by code then returns an IDictionary where the key is the code of the item and the value is the group of items with that code (Hope that makes sense!)

Here's the implementation of the method:

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

I then tried to refactor this to use ToDictionary like so:

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

I get an error when I try to compile which says I can't convert from a dictionary of string, IGrouping<string, PriceDetail> into a dictionary of string, IEnumerable<PriceDetail> .

Can someone tell me how to correctly refactor my first attempt at this method? I feel that there's a more concise way of writting it but can't figure it out!

Can you not do:

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

How about:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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