Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary<string, MyObject> or List<MyObject> with C# 3.5?

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?

like image 406
Patrick Desjardins Avatar asked Oct 28 '08 21:10

Patrick Desjardins


4 Answers

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.

like image 188
Keith Nicholas Avatar answered Nov 18 '22 00:11

Keith Nicholas


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.

like image 26
Oliver Hallam Avatar answered Nov 17 '22 23:11

Oliver Hallam


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.

like image 44
Leopold Cimrman Avatar answered Nov 18 '22 00:11

Leopold Cimrman


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

like image 29
biozinc Avatar answered Nov 18 '22 00:11

biozinc