Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dictionary with initial values using collection expressions?

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?

like image 245
nalka Avatar asked Sep 20 '25 04:09

nalka


1 Answers

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>'

like image 134
nalka Avatar answered Sep 22 '25 19:09

nalka