C# One-liner 创建一个包含一个条目的字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14454929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:50:54  来源:igfitidea点击:

One-liner to create a dictionary with one entry

c#dictionary

提问by Michael Sandler

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

我有一个将 aDictionary<int, int>作为参数的方法

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?

我怎样才能在一行中做到这一点?

采纳答案by horgh

This is it, if you do not need the aand bvariables:

就是这样,如果您不需要ab变量:

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)

请阅读如何:使用集合初始值设定项初始化字典(C# 编程指南)

回答by Sergey Berezovskiy

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