kateroh
kateroh

Reputation: 4406

IEnumerable<T> to Dictionary<string, IEnumerable<T>> using LINQ

Having IEnumerable<Order> orders, how to get a Dictionary<string, IEnumerable<Order>> using Linq, where the key is Order.CustomerName mapped to a IEnumerable of customer's orders.

orders.ToDictionary(order => order.CustomerName) is not going to work right away, since there could be multiple orders that could have the same CustomerName.

Solution: orders.ToLookup(order => order.CustomerName);

Upvotes: 20

Views: 7168

Answers (3)

Chris Sinclair
Chris Sinclair

Reputation: 23198

Just an alternative to @spender's answer, if you really want a type Dictionary<string, IEnumerable<Order>>, you could use:

Dictionary<string, IEnumerable<Order>> dictionary = orders
        .GroupBy(order => order.CustomerName)
        .ToDictionary(groupedOrders => groupedOrders.Key, 
                          groupedOrders => (IEnumerable<Order>)groupedOrders);

I'm sure there's a nicer way, but that'll do it too.

Upvotes: 13

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61912

Or you could probably simply use

orders.ToLookup(o => o.CustomerName).ToDictionary(g => g.Key)

But as Spender's answer indicates, maybe you don't need the last method, ToDictionary.

Upvotes: 5

spender
spender

Reputation: 120380

The ILookup interface is designed for this purpose, and represents a dictionary-like structure that contains many values per key. It has similar performance characteristics to those of a dictionary (i.e. it's a hashtable type structure)

You can create an ILookup using the .ToLookup extension method as follows:

ILookup<string, Order> ordersLookup = orders.ToLookup(o => o.CustomerName)

then:

IEnumerable<Order> someCustomersOrders = ordersLookup[someCustomerName];

Upvotes: 34

Related Questions