views:

1569

answers:

4

I often use Dictionary in C#2.0 with the first key as string that was containing a unique identifier.

I am learning C#3.0+ and it seems that I can now simply use a List and simply do LINQ on that object to get the specific object (with the .where()).

So, if I understand well, the Dictionary class has lost its purpose?

+11  A: 

no, a dictionary is still more efficient for getting things back out given a key.

a list you still have to iterate through the list to find what you want. A dictionary does a lookup.

Keith Nicholas
+2  A: 

IMHO the Dictionary approach will be MUCH faster than LINQ, so if you have an array with a lot of items, you should rather use Dictionary.

Leopold Cimrman
+5  A: 

If you just have a List, then doing an LINQ select will scan through every item in the list comparing it against the one you are looking for.

The Dictionary however computes a hash code of the string you are looking for (returned by the GetHashCode method). This value is then used to look up the string more efficiently. For more info on how this works see Wikipedia.

If you have more than a few strings, the initial (List) method will start to get painfully slow.

Oliver Hallam
+2  A: 

Dictionary is implemented as a hashtable. Thus it should give constant time access for lookups. List is implemented as a dynamic array, giving you linear time access.

Based on the underlying data structures, the Dictionary should still give you better performance.

MSDN docs on Dictionary

http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

and List

http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

biozinc