Use the ToDictionary<TSource, TKey>
method after you call GroupBy
to select the grouped results into the Dictionary
of the desired type.
Note that the method takes two (lambda) parameters (well, the particular overload used here, at least). The first is a selector that defines the keys (and implicitly, their type), and the second defines the values (implicitly defining their type as well).
As shown in the other answer, the GroupBy
method will return IEnumerable<IGrouping<Guid,Customer>>
, which you can iterate over directly, like so:
foreach (IGrouping<Guid, Customer> grp in customers.GroupBy(obj => obj.StoreId))
{
Guid storeID = grp.Key;
IEnumerable<Customer> customerCollection = grp;
foreach (Customer customer in customerCollection)
{
// Insert code here.
}
}
The above is likely the better approach (e.g. if your collection is lazily evaluated, it will probably retain that), but if that isn't an issue for you, the solution below will give you exactly what you asked for.
In the example below, the only line you're probably interested in is the last one. The other code is merely to facilitate running it quickly in something like LinqPad to preview the results.
// Just populating some sample data.
List<Guid> storeIDs = new List<Guid>
{
Guid.NewGuid(),
Guid.NewGuid(),
Guid.NewGuid(),
};
List<Customer> customers = new List<Customer>();
customers.Add(new Customer { Id = Guid.NewGuid(), StoreId = storeIDs[0], Name = "John" });
customers.Add(new Customer { Id = Guid.NewGuid(), StoreId = storeIDs[1], Name = "Jacob" });
customers.Add(new Customer { Id = Guid.NewGuid(), StoreId = storeIDs[2], Name = "Schmidt" });
customers.Add(new Customer { Id = Guid.NewGuid(), StoreId = storeIDs[0], Name = "May" });
customers.Add(new Customer { Id = Guid.NewGuid(), StoreId = storeIDs[1], Name = "Naomi" });
customers.Add(new Customer { Id = Guid.NewGuid(), StoreId = storeIDs[2], Name = "Tou" });
// Use the GroupBy method to group the customers by the StoreID
// Then, select the grouped data into a Dictionary.
// Use the StoreID as the key
// To make TValue a List<Customer> call ToList on the IGrouping.
Dictionary<Guid, List<Customer>> result = customers.GroupBy(obj => obj.StoreId).ToDictionary(k => k.Key, v => v.ToList());