In this article we are going to discuss difference between List and Dictionary in C#. There are many blogs, articles are available on the internet regarding it but in this particular article I will try to explain to you with as much as simplest and realistic examples so you can get a clear idea of the List and Dictionary in C#.
List<T> and Dictionary<TKey, TValue> are both part of the System.Collections.Generic namespace in C# and serve different purposes. Here are the key differences between the two.
S.No. | List | Dictionary |
---|---|---|
1 | Represents a strongly-typed list of objects that can be accessed by index. |
Represents a collection of key-value pairs. It is useful for storing data
that needs to be accessed by a unique key. |
2 | List maintains the order of elements as they are added. |
Does not guarantee the order of elements. The order of elements depends on
the hash codes of the keys. |
3 | List allows duplicate elements. |
Does not allow duplicate keys. Each key must be unique. |
4 | Use when you need an ordered collection of items that can be accessed by index, and you may need to perform list-specific operations such as sorting, reversing, or finding elements by index. | Use when you need to quickly look up values by a unique key and when the order of items is not important. |
5 | Example
|
Example
|