.NET has a lot of complex data structures. Unfortunately, some of them are quite similar, and I'm not always sure when to use one and when to use another. Most of my C# and Visual Basic books talk about them to a certain extent, but they never really go into any real detail.
What's the difference between Array, ArrayList, List, Hashtable, Dictionary, SortedList, and SortedDictionary?
Which ones are enumerable (IList -- can do 'foreach' loops)? Which ones use key/value pairs (IDict)?
What about memory footprint? Insertion speed? Retrieval speed?
Are there any other data structures worth mentioning?
I'm still searching for more details on memory usage and speed (Big-O notation).
Here are a few general tips for you:
You can use
foreach
on types that implementIEnumerable
.IList
is essentially anIEnumberable
withCount
andItem
(accessing items using a zero-based index) properties.IDictionary
on the other hand means you can access items by any-hashable index.Array
,ArrayList
andList
all implementIList
.Dictionary
,SortedDictionary
, andHashtable
implementIDictionary
.If you are using .NET 2.0 or higher, it is recommended that you use generic counterparts of mentioned types.
For time and space complexity of various operations on these types, you should consult their documentation.
.NET data structures are in
System.Collections
namespace. There are type libraries such as PowerCollections which offer additional data structures.To get a thorough understanding of data structures, consult resources such as CLRS.
I sympathise with the question - I too found (find?) the choice bewildering, so I set out scientifically to see which data structure is the fastest (I did the test using VB, but I imagine C# would be the same, since both languages do the same thing at the CLR level). You can see some benchmarking results conducted by me here (there's also some discussion of which data type is best to use in which circumstances).