List vs Dictionary in C#
Both lists and dictionaries belong to Generics collections that is they used to store collections of data. Both Dictionary <TKey, TValue> and List <T> are similar both have the random access data structures on top of the .NET framework. The Dictionary is based on a hash table that means it uses a hash lookup, which is an efficient algorithm to look up things, on the other hand, a list, have to go and check element by element until it finds the result from the beginning. In this article, we will discuss List vs Dictionary in C#.
When comparing with the List data structure, the dictionary is always a more or less fixed lookup time.
Let’s go into the details.
The Dictionary uses the hashing algorithm to search for the element (data). A Dictionary first calculates a hash value for the key and this hash value leads to the target data bucket. After that, each element in the bucket needs to be checked for equality. But actually, the list will be faster than the dictionary on the first item search because nothing to search in the first step. But in the second step, the list has to look through the first item and then the second item. So each step the lookup takes more and more time. The larger the list, the longer it takes. Of course, the Dictionary in principle has a faster lookup with O(1) while the lookup performance of a List is an O(n) operation.
The Dictionary maps a key to a value and cannot have duplicate keys, whereas a list just contains a collection of values. Also, Lists allow duplicate items and support linear traversal.
Consider the following example:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
List<int> newList = new List<int>();
Add data to the list
A list can simply add the item at the end of the existing list item.
Add data to the Dictionary
When you add data to a Dictionary, you should specify a unique key to the data so that it can be uniquely identified.
A Dictionary has a unique identifier, so whenever you look up a value in a Dictionary, the runtime must compute a hash code from the key. This optimized algorithm implemented by some low-level bit shifting or modulo divisions. We determine the point at which Dictionary becomes more efficient for lookups than List.
The Find() method of the List class loops thru each object in the list until a match is found. So, if we want to lookup a value using a key, then dictionary is better for performance over list. So, we need to use dictionary when we know the collection will be primarily used for lookups.
In this article, I try to explain List vs Dictionary in C# with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.