Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use object initializers for a list of key value pairs?

Tags:

c#

I can't figure out the syntax to do inline collection initialization for:

var a = new List<KeyValuePair<string, string>>(); 
like image 846
loyalflow Avatar asked Jul 27 '12 20:07

loyalflow


People also ask

How does Python store key-value pairs in a list?

There is no "key-value pair" as a general thing in Python. Why are you using a list instead of a dictionary? A dictionary contains key-value pairs, but there's no builtin notion of a key-value pair that's not in a dictionary.

How are Initializers executed in C#?

Initializers execute before the base class constructor for your type executes, and they are executed in the order in which the variables are declared in your class. Using initializers is the simplest way to avoid uninitialized variables in your types, but it's not perfect.

What is an object initializer?

An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.


1 Answers

Note that the dictionary collection initialization { { key1, value1 }, { key2, value2 } } depends on the Dictionary's Add(TKey, TValue) method. You can't use this syntax with the list because it lacks that method, but you could make a subclass with the method:

public class KeyValueList<TKey, TValue> : List<KeyValuePair<TKey, TValue>> {     public void Add(TKey key, TValue value)     {         Add(new KeyValuePair<TKey, TValue>(key, value));     } }  public class Program {     public static void Main()     {         var list = new KeyValueList<string, string>                    {                        { "key1", "value1" },                        { "key2", "value2" },                        { "key3", "value3" },                    };     } } 
like image 158
phoog Avatar answered Oct 09 '22 18:10

phoog