Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 438
james lewis Avatar asked Feb 08 '12 15:02

james lewis


1 Answers

Can you not do:

priceDetails.GroupBy(priceDetail => priceDetail.Code)                .ToDictionary(group => group.Key, group => group.ToList()) 
like image 152
bobwah Avatar answered Oct 08 '22 15:10

bobwah