Collecting Collections: The Lookup Collection
Every once in a while, I end up with a bunch of collections in memory and need the ability to pick the collection I want by name. For example, I might need a bunch of Customer collections, one for each city where I have a customer.
Furthermore, I'd like to have those collections organized into a larger collection called CityCusts so I can pull out all of the Customers for any specific city.
The code I want to use to retrieve the Customers collection for a city would look like this:
Dim lstCusts As List(Of Customer)
lstCusts = CityCusts("Regina")
I could build that CityCusts collection myself by defining a Dictionary collection that holds values that are, themselves, a collection of Customers:
Private CityCusts As Dictionary(Of String, List(Of Customer))
Initializing the individual collections for each Dictionary entry and adding the right customer to the right City collection would be a pain, though. Even using LINQ's Group By syntax is awkward, in both languages.
Fortunately, the Lookup collection makes building that collection a snap. To declare a Lookup class you just specify the type of the Dictionary's key (pretty much always a string) and the type held in the collection. Here's the declaration to create a Lookup collection that holds a collection of Customers associated with a city:
Private CityCusts As Lookup(Of String, Customer)
To load the class, I just start with a collection of Customer objects and call the collection's ToLookup method. I must pass the method a lambda expression that specifies which property to use to organize the Customers collection.
This example creates collections of Customer objects that share the same value in their City property and then stores those collections in CityCusts, under the name of the shared city:
CityCusts = Custs.ToLookup(Function(c) c.City)
In C#, the two lines of code to declare and load the collection would look like this:
private Lookup<string, Customer> CityCusts;
CityCusts = Custs.ToLookup(c => c.City);
Bada bing (as they say), bada boom.
Posted by Peter Vogel on 03/19/2018 at 5:51 AM