Group the collection and return the dictionary

I wrote a method that takes a set of elements (price elements - each element has a quantity and a code) and groups them by code, and then returns an IDictionary, where the key is the element code and the value is a group of objects with this code (I 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; } 

Then I tried to reorganize this to use ToDictionary as follows:

 // 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 that I can not convert from the dictionary string, IGrouping<string, PriceDetail> to the dictionary string, IEnumerable<PriceDetail> .

Can someone tell me how to properly reorganize my first attempt at this method? I feel that there is a more concise way to write this, but I can't figure it out!

+7
source share
2 answers

What about:

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

Can you do:

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

All Articles