james lewis
james lewis

Reputation: 2532

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!

Upvotes: 41

Views: 32178

Answers (2)

bobwah
bobwah

Reputation: 2568

Can you not do:

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

Upvotes: 99

Jakub Konecki
Jakub Konecki

Reputation: 46008

How about:

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

Upvotes: 20

Related Questions