Sunday, August 31, 2014

List vs. Dictionary

List is great when you do not have unique key for each item and the order they are added is important. If you need to be able to get the 3rd item of a list and return it, then its very useful. Its good for loops and iterations. A List will dynamically resize (no need to manage size manually). Lists are a Generic type and can hold anything. From the example above, think of a List as a bunch of different colored markers but that all have the same color outside. You have to grab the "5th" one, pick it up, remove the cap, and see what it is. But! It is in order, and the 5th marker will always be the 5th marker no matter what. Now get me a BLUE marker. Well.. you can iterate over this list and say you want to loop until you find blue. But then you have to pick up every marker and ask "Is it blue?".. and that is not the best design. Or the most logical.

Dictionary is a list with a guaranteed unique key. Both adding and getting are quicker when using a list. However, there is no order of the items.. so cannot iterate over the Dictionary. Like most other pieces of data, the same key is not allowed to be used twice. Now think of this disordered mess as a bunch of messy markers scattered into a pile (example above). They are not in order. But they do have a key.. they "key" here is the outside of the marker. It is labeled with certain colors on the outside so you know what it is.. and you do not have to uncap every one and check them to know. I want you to get a BLUE marker for me. You look and you can easily see from the "key" (outside of the marker color) which one is blue. Try and get me the 5th marker.. well-- you can't, there is no order.


You can see how list and dictionary both have their uses! It depends on the situation, as always :)