Actually I need something like List<KeyValuePair<T, U>> but I want to be able to initialize it like dictionary (i.e. without writing new KeyValuePair every time). Like this:
Dictionary<string, string> dic = new Dictionary<string, string>
{
{ "key1", "value1"},
{ "key2", "value2"}
};
EDIT: It turns out .NET does have a combination list/dictionary type already:
OrderedDictionary. Unfortunately this is a non-generic type, making it rather less attractive in my view. However, it retains the insertion order if you just callAddrepeatedly.It’s a little strange as calling
Adddoes not affect entries where a key already exists, whereas using the indexer to add a key/value pair will overwrite a previous association. Basically it doesn’t seem like a terribly nice API, and I would personally still avoid it unless your use case exactly matches its behaviour.No, .NET doesn’t have any insertion-order-preserving dictionaries. You could always write your own list-based type with the relevant
Addmethod. This might even be one of the few places I’d consider extending an existing type:Then:
An alternative is to use composition, but my gut feeling is that this is a reasonable use of inheritance. I can’t place why I’m happy in this case but not usually, mind you…