> Was there really no better way to create tuples before?
Here are some other options for code like the grandparent post. I tend to either live with the boilerplate or use a local function.
1. Use a collection initializer extension method (https://news.ycombinator.com/item?id=26641997).
2. Define a local helper function.
KeyValuePair<string, int> KeyValue(string key, int value)
{
return new KeyValuePair<string, int>(key, value);
}
// new w/local function
var x = new List<KeyValuePair<string, int>>
{
KeyValue("a", 1),
KeyValue("b", 2)
};
3. Use an array of C# 7 tuples and convert them in a loop or query.
4. Use generics to infer the argument types à la Tuple.Create. This technique can be helpful for using anonymous types with collections.
//KeyValuePair.cs
internal static class KeyValuePair
{
public static KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value)
{
return new KeyValuePair<TKey, TValue>(key, value);
}
}
// new w/helper class
var x = new List<KeyValuePair<string, int>>
{
KeyValuePair.Create("a", 1),
KeyValuePair.Create("b", 2)
};