What is the difference between Tuple, Dictionary and List in C#?
This question already has an answer here.
I was trying to use Tuple in my application. So I want to differentiate a Tuple, Dictionary and List.
Dictionary<int, string> dic = new Dictionary<int, string>();
Tuple<int, string> tuple = new Tuple<int, string>();
List<int> list = new List<int>();
What is the difference between these three?
First, AFAIK, there isn't any list that takes two type parameters - so your List could either be a List<int>
or List<string>
(or a SortedList<int,string>
, but that's a different class).
A Tuple<T1, T2>
holds two values - one int and one string in this case. You can use a Tuple to bind together items (that might be of different
types). This may be useful in many situations, like, for instance, you want to return more than one value from a method.
I personally hate the Item1
, Item2
property names, so I would probably use a wrapper class around Tuples in my code.
A Dictionary<TKey, TValue>
is a collection of KeyValuePair<TKey, TValue>
. A Dictionary maps keys to values, so that you can have, for instance, a dictionary of people and for each person have their SSN as a key.
A List<T>
is a collection of T
.
You can get individual items by using the index, the Find
method, or simply LINQ (since it implements IEnumerable<T>
).
While the answer you have linked discusses the differentiation between List<T>
and Dictionary<int, T>
, Tuple<int, string>
is not addressed.
From MSDN
Represents a 2-tuple, or pair.
A tuple is a pair of values, opposed to the other types, which represent sort of collections. Think of a method, which returns an error code and string for the last error (I would not write the code this way, but to get the idea)
Tuple<int, string> GetLastError()
{
...
}
Now you can use it like
var lastError = GetLastError();
Console.WriteLine($"Errorcode: {lastError.Item1}, Message: {lastError.Item2}");
This way you do not have to create a class, if you want to return a compound value.
Please Note: As of C# 7 there is a newer, more concise syntax for returning tuples.
A list can store a sequence of objects in a certain order such that you can index into the list, or iterate over the list. List is a mutable type meaning that lists can be modified after they have been created.
A tuple is similar to a list except it is immutable. There is also a semantic difference between a list and a tuple. To quote Nikow's answer:
Tuples have structure, lists have order.
A dictionary is a key-value store. It is not ordered and it requires that the keys are hashable. It is fast for lookups by key.