Junior — Middle
What are the differences between methods of extracting information from a list and from a dictionary in a programming language?
sobes.tech AI
Answer from AI
In C#, extracting information from a list (List<T>) and a dictionary (Dictionary<TKey, TValue>) differs in the way of access:
-
List (List<T>): elements are accessible by index, for example
list[0]. It is an ordered collection where the order of elements matters. -
Dictionary (Dictionary<TKey, TValue>): elements are accessible by key, for example
dictionary[key]. It is an unordered collection of key-value pairs where the key is unique.
Example:
List<string> list = new List<string> { "apple", "banana" };
string firstItem = list[0]; // "apple"
Dictionary<int, string> dict = new Dictionary<int, string> { {1, "one"}, {2, "two"} };
string value = dict[1]; // "one"
Thus, a list is convenient for sequential access by position, while a dictionary is suitable for quick access by a unique key.