Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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);

like image 659
kateroh Avatar asked Sep 25 '12 17:09

kateroh


2 Answers

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];
like image 186
spender Avatar answered Sep 29 '22 11:09

spender


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.

like image 45
Chris Sinclair Avatar answered Sep 29 '22 13:09

Chris Sinclair