Is there an easier way to initialize a List <KeyValuePair <T, U >> as a dictionary <T, U>?

Actually I need something like List<KeyValuePair<T, U>> , but I want it to be able to initialize it like a dictionary (i.e. without writing new KeyValuePair every time). Like this:

 Dictionary<string, string> dic = new Dictionary<string, string> { { "key1", "value1"}, { "key2", "value2"} }; 
+6
c #
source share
3 answers

EDIT: It turns out that .NET already has a combinational list / dictionary: OrderedDictionary . Unfortunately, this is not a general type, which makes it less attractive, in my opinion. However, it keeps the insertion order if you just call Add several times.

A bit strange, since the Add call does not affect records where the key already exists, while using an indexer to add a key / value pair will overwrite the previous relationship. Basically, this does not seem like a terribly nice API, and I personally would have avoided it if your use case does not exactly match its behavior.


No, .NET does not contain dictionaries that preserve the placement order. You can always write your own type based on a list using the appropriate Add method. This may even be one of the few places that I would consider expanding an existing type:

 public class KeyValueList<TKey, TValue> : List<KeyValuePair<TKey, TValue>> { public void Add(TKey key, TValue value) { Add(new KeyValuePair<TKey, TValue>(key, value)); } } 

Then:

 var list = new KeyValueList<string, string> { { "key1", "value1"}, { "key2", "value2"} }; 

An alternative is to use composition, but my gut feeling is that it is a wise use of inheritance. I can’t say why I am happy in this case, but not usually, mind you ...

+9
source share

Since you do not have a dictionary, you cannot use the initiailzer dictionary. You have a list so you can use the list initializer that will be closest to you:

 var l = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("key1", "value1"), new KeyValuePair<string, string>("key2", "value2"), }; 

Here's the minimum requirement for using a vocabulary initializer: the class must implement IEnumerable , and the class must have a public Add method that takes 2 arguments (where the first argument represents the key and the second argument is the value). This way you can write your own class that satisfies these requirements, and you can use the syntax that you specified in your question.

+2
source share

The code you typed works fine - then to the Mads Togersen post on the implementation of the initializers of the collection, the compiler matches the delimited records ( {"key1", "value1"} above) to the Add method in the collection with the same signature - in this case, Dictionary .Add (TKey, TValue) .

0
source share

All Articles