C# Dictionary Shorthand (Initialisation syntax)

Dictionary’s in C# are great, they’re basically a hash table and give us constant lookup times. But dictionary initialisation isn’t obvious and I often have to lookup how to create new dictionaries while initialising them with values.

The following should hopefully serve as an easy reminder of the shorthand for initialising a c# dictionary.

Example 1: Dictionary shorthand for Dictionary<string, string>

var capitals = new Dictionary<string, string>()
{
    { "UK", "London" },
    { "France", "Paris" },
    { "Germany", "Berlin" }
};

Example 2: Dictionary shorthand for Dictionary<int, string>

var anniversaries = new Dictionary<int, string>()
{
    { 25, "Silver" },
    { 40, "Ruby" },
    { 50, "Gold" }
};

Example 3: Alternative Dictionary shorthand syntax (C# 6.0)

var anniversaries = new Dictionary<int, string>()
{
    [25] = "Silver",
    [40] =  "Ruby",
    [50] =  "Gold"
};

This syntax was introduced in C# 6.0 so if you find it doesn’t work for you, try updating the C# version in your project. If you use Visual Studio 2019 it should prompt you to update automatically.

Example 4: Dictionary from a List<int, string>

Another common use case is to create a dictionary from a list:

var myList = new List<KeyValuePair<int, string>>()
{
    new KeyValuePair<int, string>(25, "Silver"),
    new KeyValuePair<int, string>(40, "Ruby"),
    new KeyValuePair<int, string>(25, "Gold"),
};

var myDict = myList.ToDictionary(x => x.Key, x => x.Value);

Example 5: Dictionary from an IGrouping<string, object>

Finally the one that always trips me up, using a group by and getting the results back as a dictionary. In other words, C# GroupBy to Dictionary:

var results = new List<GameResult>()
{
    new GameResult { Name = "George", Points = 10 },
    new GameResult { Name = "George", Points = 10 },
    new GameResult { Name = "Ben", Points = 13 },
    new GameResult { Name = "Ben", Points = 17 },
};
 
Dictionary<string, int> totals = results
    .GroupBy(r => r.Name)
    .ToDictionary(g => g.Key, g => g.Sum(x => x.Points));

foreach (var total in totals)
{
    Console.WriteLine($"{total.Key} has {total.Value} points in total.");
}

Which returns:

George has 20 points in total.
Ben has 30 points in total.

Digression: GroupBy without aggregation

The reason this trips me up is because I’m used to SQL where you specify the aggregation at the front, e.g.:

Select Name, Max(Points)
from results
group by Name

But with C#’s linq, the group by gives you an IGrouping containing all the results, unaggregated. It’s then up to you to aggregate them afterwards, if so desired. Of course, you could always opt to do no aggregation:

var results = new List<GameResult>()
{
    new GameResult { Name = "George", Points = 10 },
    new GameResult { Name = "George", Points = 10 },
    new GameResult { Name = "Ben", Points = 13 },
    new GameResult { Name = "Ben", Points = 17 },
};
 
IEnumerable<IGrouping<string, GameResult>> totals =
    results.GroupBy(r => r.Name);
 
foreach (var group in totals)
{
    Console.WriteLine($"{group.Key} has points:");
    foreach (var item in group)
    {
        Console.WriteLine(item.Points);
    }
}

Which returns:

George has points:
10
10
Ben has points:
13
17

It’s not obvious to me how you’d get output like that in SQL!

One Reply to “C# Dictionary Shorthand (Initialisation syntax)”

Leave a Reply

Your email address will not be published. Required fields are marked *