Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner to create a dictionary with one entry

Tags:

c#

dictionary

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?

like image 456
Michael Sandler Avatar asked Jan 22 '13 09:01

Michael Sandler


People also ask

How do you make a dictionary one line?

Python Update Dictionary in One Line Solution: Use the square bracket notation dict[key] = value to create a new mapping from key to value in the dictionary. There are two cases: The key already existed before and was associated to the old value_old .

How to create dictionary entry Python?

To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {} and separate them using a comma ( , ). Each entry consists of a key and a value, also known as a key-value pair. Note: The values can belong to any data type and they can repeat, but the keys must remain unique.

How do you initialize a new dictionary?

Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.


2 Answers

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)

like image 104
horgh Avatar answered Oct 03 '22 03:10

horgh


var param = new Dictionary<int, int>() { { 5, 6 } };     
like image 34
Sergey Berezovskiy Avatar answered Oct 03 '22 03:10

Sergey Berezovskiy