Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would you use a List<KeyValuePair<T1, T2>> instead of a Dictionary<T1, T2>?

Tags:

c#

dictionary

What is the difference between a List of KeyValuePair and a Dictionary for the same types? Is there an appropriate time to use one or the other?

like image 534
Corpsekicker Avatar asked Nov 20 '09 08:11

Corpsekicker


People also ask

What is the difference between KeyValuePair and dictionary C#?

KeyValuePair is the unit of data stored in a Hashtable (or Dictionary ). They are not equivalent to each other. A key value pair contains a single key and a single value. A dictionary or hashtable contains a mapping of many keys to their associated values.

Is dictionary A list of key-value pairs?

Dictionary is generic type that contains a collection of key-value pairs. Dictionary is fast for lookup operations, because is using hash function internally. That means, all the keys must be unique in dictionary.

When would you use a key-value pair?

A key-value pair (KVP) is a set of two linked data items: a key, which is a unique identifier for some item of data, and the value, which is either the data that is identified or a pointer to the location of that data. Key-value pairs are frequently used in lookup tables, hash tables and configuration files.

What is the difference between dictionary and Hashtable in C#?

In Hashtable, you can store key/value pairs of the same type or of the different type. In Dictionary, you can store key/value pairs of same type. In Hashtable, there is no need to specify the type of the key and value. In Dictionary, you must specify the type of key and value.


2 Answers

When you don't need fast lookups on key - maintaining the hashtable used by Dictionary has a certain overhead.

like image 170
Pavel Minaev Avatar answered Sep 21 '22 01:09

Pavel Minaev


In short, the list does not enforce uniqueness of the key, so if you need that semantic then that's what you should use.

like image 29
RCIX Avatar answered Sep 21 '22 01:09

RCIX