我可以为 Dictionary < TKey,TValue > 条目使用集合初始值设定项吗?

我想为下一段代码使用一个集合初始值设定项:

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;
}

所以通常应该是这样的:

return new Dictionary<int, string>
{
1, "Adam",
2, "Bart"
...

但这个问题的正确语法是什么呢?

39218 次浏览
return new Dictionary<int, string>
{
{ 1, "Adam" },
{ 2, "Bart" },
...

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:

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!" };
var names = new Dictionary<int, string> {
{ 1, "Adam" },
{ 2, "Bart" },
{ 3, "Charlie" }
};

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 :

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>

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.

As well as being less verbose you can of course add extra methods to this class for whatever you might want.

In the following code example, a Dictionary<TKey, TValue> is initialized with instances of type 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

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):

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",
};

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" }


};