views:

116

answers:

4

I have a list of objects and I need to find an object as quickly as possible (by it's name property). What data-structure should I use? I know I can use a Dictionary, but there wont ever be more than 10 items in the list, and if I remember correctly the dictionary is implemented as an array if the collection contains 10 items or less.

Thanks.

+5  A: 

MSDN recommends the ListDictionary for collections with 10 items or less:

This is a simple implementation of IDictionary using a singly linked list. It is smaller and faster than a Hashtable if the number of elements is 10 or less. This should not be used if performance is important for large numbers of elements.

Anna Lear
+1 This sounds perfect for the purpose!
Will Marcouiller
That recommendation might be out of date since ListDictionary is not generic. The docs have said that since the beginning.
Mike Two
Thank you Anna, that seems to be a perfect answer to my question.
Mikael Sundberg
+2  A: 

You may want to consider the System.Collections.Specialized.ListDictionary if you are certain there will be less than ten items.

Also consider the System.Collections.Specialized.HybridDictionary which switches behaviour (with a small overhead) should the size increase above a threshold, handy if your assumption is wrong.

Paul Ruane
A: 

Why not just use a Hashtable? It's in the System.Collections namespace.

chamiltongt
Because both the Dictionary<> and Hashtable classes are implementations of hashtables and have an overhead in having to calculate the hashcode for each item which only pays for itself when the collection is not trivially small.
Paul Ruane
A: 

Since you want fastest possible lookup by a property you should use Dictionary<Key, Value>. The size doesn't hurt you if you want fast lookup. It's not that a Dictionary<Key, Value> of just 10 items or less is taking up a ton of memory. Dictionary<Key, Value> has a constructor that takes an int to set the capacity.

Mike Two