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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With