This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

List vs Dictionary


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.

Difference Between Hashtable and Dictionary in C#

S.No. List Dictionary
1 Represents a strongly-typed list of objects that can be accessed by index.
List vs Dictionary in C#
Represents a collection of key-value pairs. It is useful for storing data that needs to be accessed by a unique key.
List vs Dictionary in C#
2 List maintains the order of elements as they are added.
List vs Dictionary in C#
Does not guarantee the order of elements. The order of elements depends on the hash codes of the keys.
List vs Dictionary in C#
3 List allows duplicate elements.
List vs Dictionary in C#
Does not allow duplicate keys. Each key must be unique.
List vs Dictionary in C#
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
List list = new List { "one", "two", "three" };
list.Add("four");
foreach (string item in list) {
    Console.WriteLine(item);
}
Example
Dictionary dictionary = new Dictionary {
    { 1, "one" },
    { 2, "two" },
    { 3, "three" }
};
dictionary.Add(4, "four");
foreach (KeyValuePair kvp in dictionary) {
    Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}

Next