C# 我可以为 Dictionary<TKey, TValue> 条目使用集合初始值设定项吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/495038/
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
Can I use a collection initializer for Dictionary<TKey, TValue> entries?
提问by Gerrie Schenck
I want to use a collection initializer for the next bit of code:
我想为下一段代码使用集合初始值设定项:
public Dictionary<int, string> GetNames()
{
Dictionary<int, string> names = new Dictionary<int, string>();
names.Add(1, "Adam");
names.Add(2, "Bart");
names.Add(3, "Charlie");
return names;
}
So typically it should be something like:
所以通常它应该是这样的:
return new Dictionary<int, string>
{
1, "Adam",
2, "Bart"
...
But what is the correct syntax for this?
但是什么是正确的语法呢?
采纳答案by bruno conde
var names = new Dictionary<int, string> {
{ 1, "Adam" },
{ 2, "Bart" },
{ 3, "Charlie" }
};
回答by ybo
return new Dictionary<int, string>
{
{ 1, "Adam" },
{ 2, "Bart" },
...
回答by Anton Gogolev
The syntax is slightly different:
语法略有不同:
Dictionary<int, string> names = new Dictionary<int, string>()
{
{ 1, "Adam" },
{ 2, "Bart" }
}
Note that you're effectively adding tuples of values.
请注意,您正在有效地添加值的元组。
As a sidenote: collection initializers contain arguments which are basically arguments to whatever Add()function that comes in handy with respect to compile-time type of argument. That is, if I have a collection:
作为旁注:集合初始值设定项包含的参数基本上是任何Add()函数的参数,这些函数在编译时类型的参数方面派上用场。也就是说,如果我有一个集合:
class FooCollection : IEnumerable
{
public void Add(int i) ...
public void Add(string s) ...
public void Add(double d) ...
}
the following code is perfectly legal:
以下代码是完全合法的:
var foos = new FooCollection() { 1, 2, 3.14, "Hello, world!" };
回答by Simon_Weaver
If you're looking for slightly less verbose syntax you can create a subclass of Dictionary<string, object>
(or whatever your type is) like this :
如果您正在寻找稍微不那么冗长的语法,您可以创建一个子类Dictionary<string, object>
(或任何您的类型),如下所示:
public class DebugKeyValueDict : Dictionary<string, object>
{
}
Then just initialize like this
然后像这样初始化
var debugValues = new DebugKeyValueDict
{
{ "Billing Address", billingAddress },
{ "CC Last 4", card.GetLast4Digits() },
{ "Response.Success", updateResponse.Success }
});
Which is equivalent to
这相当于
var debugValues = new Dictionary<string, object>
{
{ "Billing Address", billingAddress },
{ "CC Last 4", card.GetLast4Digits() },
{ "Response.Success", updateResponse.Success }
});
The benefit being you get all the compile type stuff you might want such as being able to say
好处是您可以获得您可能想要的所有编译类型的东西,例如能够说
is DebugKeyValueDict
instead of is IDictionary<string, object>
is DebugKeyValueDict
代替 is IDictionary<string, object>
or changing the types of the key or value at a later date. If you're doing something like this within a razor cshtml page it is a lot nicer to look at.
或在以后更改键或值的类型。如果你在一个 razor cshtml 页面中做这样的事情,它会更好看。
As well as being less verbose you can of course add extra methods to this class for whatever you might want.
除了不那么冗长之外,您当然可以根据需要向此类添加额外的方法。
回答by Bellash
In the following code example, a Dictionary<TKey, TValue>
is initialized with instances of type StudentName
.
在下面的代码示例中, aDictionary<TKey, TValue>
使用类型的实例进行初始化StudentName
。
Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()
{
{ 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
{ 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
{ 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
};
from msdn
来自msdn
回答by Nate Cook
The question is tagged c#-3.0
, but for completeness I'll mention the new syntax available with C# 6 in case you are using Visual Studio 2015 (or Mono 4.0):
问题被标记为c#-3.0
,但为了完整起见,我将提及 C# 6 可用的新语法,以防您使用 Visual Studio 2015(或 Mono 4.0):
var dictionary = new Dictionary<int, string>
{
[1] = "Adam",
[2] = "Bart",
[3] = "Charlie"
};
Note: the old syntax mentioned in other answers still works though, if you like that better. Again, for completeness, here is the old syntax:
注意:如果您更喜欢,其他答案中提到的旧语法仍然有效。同样,为了完整性,这里是旧语法:
var dictionary = new Dictionary<int, string>
{
{ 1, "Adam" },
{ 2, "Bart" },
{ 3, "Charlie" }
};
One other kind of cool thing to note is that with either syntax you can leave the last comma if you like, which makes it easier to copy/paste additional lines. For example, the following compiles just fine:
需要注意的另一件很酷的事情是,无论哪种语法,您都可以根据需要保留最后一个逗号,这样可以更轻松地复制/粘贴其他行。例如,以下编译就好了:
var dictionary = new Dictionary<int, string>
{
[1] = "Adam",
[2] = "Bart",
[3] = "Charlie",
};
回答by Debendra Dash
Yes we can use collection initializer in dictionary.If we have a dictionary like this-
是的,我们可以在字典中使用集合初始值设定项。如果我们有这样的字典-
Dictionary<int,string> dict = new Dictionary<int,string>();
dict.Add(1,"Mohan");
dict.Add(2, "Kishor");
dict.Add(3, "Pankaj");
dict.Add(4, "Jeetu");
We can initialize it as follow.
我们可以按如下方式初始化它。
Dictionary<int,string> dict = new Dictionary<int,string>
{
{1,"Mohan" },
{2,"Kishor" },
{3,"Pankaj" },
{4,"Jeetu" }
};