Dictionary of Dictionaries? WTF?
Sunday, June 21, 2009 8:37 PM
Have you ever wanted to use a Dictionary of Dictionaries? What the heck are you doing with that you might ask? Read on please! :>
The last few weeks I've been working on something at work where I needed to map old primary keys (PKs) to new PKs. Sounds easy enough eh? The problem with that is getting the keys in by table name and getting out the new PK when you pass in the old PK. Getting dizzy yet? And I've been playing with this for a little while and I'm still dizzy! DOH! But it's not that hard, read on for a quick discussion on dictionaries of dictionaries.
Here's the pictorial representation of what I'm trying to model in memory.
As you can see, the idea is, there is a Dictionary<string, Dictionary<int, int>>, yup, a dicionaries of dictionaries. The idea is the string is the table name (Customers, Orders and Products), and then each will have it's own Dictionary of source PKs and destination PKs. So when I wanted to "look up" the NEW/Destination PK of Product 234, you would pass in "Products" with 234, then the dictionary would pass you back 567. Simple really (in theory), but implementing was interesting, fun! but interesting.
The main challenges were minor but will still trip you up. For example, you have to make sure you properly instantiate the <int, int> dictionary BEFORE trying to use it! Ya, easy to say now but I forgot to do it, once you hit the runtime error you do a V8 DOH! moment before fixing it, but just something to remember.
PrimaryKeyMappings pks = new PrimaryKeyMappings();
Dictionary<int, int> contacts = new Dictionary<int, int>();
contacts.Add( 1, 11 );
contacts.Add( 2, 22 );
contacts.Add( 3, 33 );
contacts.Add( 4, 44 );
pks.PKMappings.Add( "Contacts", contacts );
Dictionary<int, int> orders = new Dictionary<int, int>( 3 );
orders.Add( 7, 77 );
orders.Add( 8, 88 );
orders.Add( 9, 99 );
pks.PKMappings.Add( "Orders", orders );
Dictionary<int, int> products = new Dictionary<int, int>( 10 );
products.Add( 123, 456 );
products.Add( 234, 567 );
products.Add( 345, 678 );
products.Add( 456, 789 );
products.Add( 567, 890 );
pks.PKMappings.Add( "Products", products );
Adding keys which are already there can be a problem with Dictionarys DOH! HAHA. So you have to use he ContainsKey() method to make sure you don't add twice.
if( !productsWithAdditions.ContainsKey( 456 ) )
productsWithAdditions.Add( 456, 4567 );
Console.WriteLine( "No need to add it since it's already there" );
Well, that's about all for Dicionaries for the moment. I hope you enjoy the code. Now it's time to go grab a coffee and get coding! :>
Source Code: http://www.pchenry.com:8080/svn/blog/trunk/2009/DictionaryBasics