One-liner to create a dictionary with one entry

C#Dictionary

C# Problem Overview


I have a method which takes a Dictionary<int, int> as a parameter

public void CoolStuff(Dictionary<int, int> job)

I want to call that method with one dictionary entry, such as

int a = 5;
int b = 6;
var param = new Dictionary<int, int>();
param.Add(a, b);
CoolStuff(param);

How can I do it in one line?

C# Solutions


Solution 1 - C#

This is it, if you do not need the a and b variables:

var param = new Dictionary<int, int> { { 5, 6 } };

or even

CoolStuff(new Dictionary<int, int> { { 5, 6 } });

Please, read How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)

Solution 2 - C#

var param = new Dictionary<int, int>() { { 5, 6 } };    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael SandlerView Question on Stackoverflow
Solution 1 - C#horghView Answer on Stackoverflow
Solution 2 - C#Sergey BerezovskiyView Answer on Stackoverflow