.NET data structures: ArrayList, List, HashTable,

2020-01-25 03:18发布

.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).

14条回答
男人必须洒脱
2楼-- · 2020-01-25 03:46

Here are a few general tips for you:

  • You can use foreach on types that implement IEnumerable. IList is essentially an IEnumberable with Count and Item (accessing items using a zero-based index) properties. IDictionary on the other hand means you can access items by any-hashable index.

  • Array, ArrayList and List all implement IList. Dictionary, SortedDictionary, and Hashtable implement IDictionary.

  • 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.

查看更多
男人必须洒脱
3楼-- · 2020-01-25 03:46

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).

查看更多
登录 后发表回答