C# 12 introduced collection expressions and now you can write code like List<int> l = [1, 2, 3];
.
When it comes to using them with dictionaries, it seems to work fine when creating an empty one with Dictionary<string, int> d = [];
.
However, when it comes to creating one with initial values, none of these seem to compile:
Dictionary<string, int> d = [{ "a", 1 }];
Dictionary<string, int> d = [("a", 1)];
Dictionary<string, int> d = [new KeyValuePair<string, int>("a", 1)];
Is there a way I can create a dictionary containing initial values using collection expressions?
Dictionary<string, int> d = [new KeyValuePair<string, int>("a", 1)];
yields this error message:
Collection expression type 'Dictionary<string, int>' must have an instance or extension method 'Add' that can be called with a single argument.
It leads to a solution to make it compile: creating the following extension method
public static void Add<TKey, TValue>(this Dictionary<TKey, TValue> source, KeyValuePair<TKey, TValue> added)
{
source.Add(added.Key, added.Value);
}
Note that this extension method will also enable the usage of spread elements with dictionaries like Dictionary<string, int> d2 = [..d];
Similarly, based on the above error message, one might expect the same kind of extension method using a tuple (so (TKey Key, TValue Value)
instead of KeyValuePair<TKey, TValue>
) to enable Dictionary<string, int> d = [("a", 1)];
but (because Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>> and not IEnumerable<(TKey, TValue)>, more here) it will instead yield:
CS0029 Cannot implicitly convert type '(string, int)' to 'System.Collections.Generic.KeyValuePair<string, int>'
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