I can't figure out the syntax to do inline collection initialization for:
var a = new List<KeyValuePair<string, string>>();
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.
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.
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.
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" }, }; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With