ChocolateSnow
ChocolateSnow

Reputation: 199

What are the differences between a list, sorted list, and an array list? (c#)

From what I've read, a list, sorted list, and an array list have many things in common, but at the same time have a few differences.

I would like to know: What are the differences between them that a beginner should know? Why choose one over the other? And what are some good habits to form when using them in code?

Thank you for your time.

Upvotes: 17

Views: 20780

Answers (2)

user1968030
user1968030

Reputation:

From MSDN:

A SortedList element can be accessed by its key, like an element in any IDictionary implementation, or by its index, like an element in any IList implementation.

A SortedList object internally maintains two arrays to store the elements of the list; that is, one array for the keys and another array for the associated values. Each element is a key/value pair that can be accessed as a DictionaryEntry object. A key cannot be null, but a value can be.

Also for choosing best collection you can see this.

enter image description here

Upvotes: 28

GreatAndPowerfulOz
GreatAndPowerfulOz

Reputation: 1775

with List<T> and SortedList<T> you can specify the type of the element and are generally easier to use because of that. ArrayList is legacy, and holds objects but you must cast them to the contained type yourself.

SortedList<T> as the name implies is a sorted list of type T. Use it when you want a sorted list. Use List<T> when a sorted ordering is unnecessary or when a general collection of T is sufficient or you provide your own sorting mechanism. SortedList<T> will be slower on adding items then List<T>, so only use it when necessary.

Upvotes: 2

Related Questions