Home > Software design >  Dictionary vs List
Dictionary vs List

Time:10-19

The list in C# can be traversed by for, but is there a special reason why Dictionary can be referred to as a[0] with a declaration of <int, int> type, but not for for, but only with foreach? And why can the List be toured with the for repeat statement?

CodePudding user response:

If you refer to the documentation for a list, you can see that it declares an indexer:

public T this[int index] { get; set; }

This allows us to access the elements of the list by index, e.g.:

int item = listOfInt[5]; // this will retrieve the 6th item in the list

To retrieve the item, the get method of the indexer is called and the index value 5 is passed in. This is how it knows which item you want.

Now, if you refer to the documentary for a dictionary, you can see that it also declares an indexer:

public TValue this[TKey key] { get; set; }

But you'll note that this indexer is different: instead of taking an int value for index, it takes a dictionary key. This allows you to access items by key (e.g. Person p = dictionaryOfPeople["Bob"];).

Yes, you can declare multiple indexers that differ by the indexing argument (index or key in the previous examples), but this would essentially prevent using an indexer for Dictionary<int, int> because it would be ambiguous which indexer you were referring to: is it the index? is it the key? This is why such an indexer can't exist on a dictionary.

The reason foreach works is that it operates on types that implement an IEnumerable interface. Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>> (source), so when we do a foreach over a dictionary our items are KeyValuePair<TKey, TValue> objects. A List<Person> implements IEnumerable<Person> so when we do a foreach over this, our items are Person.

CodePudding user response:

The point of a List and Dictionary are different. A List is basically supposed to be a dynamic array, so it provides access by index like an array does but it also allows items to be added and removed. The point of a Dictionary is to access items by key rather than by index. If you declare the key type to be int then you can access a value by an int key but it's still a key, not an index. Indexes in a List start at zero and are sequential, while keys in a Dictionary can be any value of the specified type, so int keys in a Dictionary don't necessarily have to include zero and don't have to be sequential. An example of a use for a Dictionary would be a list of Employee objects keyed on an employee ID.

  •  Tags:  
  • c#
  • Related