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