Today I responded to a question on the Microsoft Visual C# Developer Center. The person (I’ll call him Mr. X) wanted to break a generic list of objects into separate generic lists, where each of the new lists contained entries with a common value for a particular property. He wanted to combine these new lists into a list of lists. I responded that he might consider creating a dictionary instead of creating a list of lists, but that, if he really wanted a list of lists, he could use the dictionary to create it. Let’s look at the details of how we might accomplish this. (Note: if an image below is too small for you to read, just double-click it. Then, when you are done viewing it, just navigate back to the blog page.)
Mr. X was working with a CarType class consisting of four elementary properties. Starting from a list of CarType objects,
he wanted to break this into separate lists, where the entries in each list have a common value for ID.
So … the first thing we do is to create the original list:
Then we create a dictionary of type Dictionary<int,List<CarType>> and load it in a simple foreach loop. Note that when we
encounter an entry in the original list for which there is no existing list in the dictionary, we first create the requisite new list.
If we are doing this in a console application, we can verify that the dictionary lists were properly created with the following two-level loop:
Note that each entry in the dictionary is of type KeyValuePair<int,List<CarType>>. This object enables us to easily retrieve the key (int) and the corresponding value (List<CarType>) of each dictionary entry.
If we wish to put the final results in a list of lists, we just create the list of lists and dump the dictionary contents into it as follows:
The validation is similar to that for the dictionary. Here is the final result, expressed in the Main method of a console application:
Go ye forth and make lists!

No comments:
Post a Comment