简体   繁体   English

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

[英]Can I use a collection initializer for Dictionary<TKey, TValue> entries?

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? 但是这个的正确语法是什么?

var names = new Dictionary<int, string> {
  { 1, "Adam" },
  { 2, "Bart" },
  { 3, "Charlie" }
};

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. 作为旁注:集合初始值设定项包含的参数基本上是任何Add()函数的参数,该函数对于编译时参数类型而言非常方便。 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!" };
return new Dictionary<int, string>
{ 
   { 1, "Adam" },
   { 2, "Bart" },
   ...

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

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. 如果你在剃刀cshtml页面中做这样的事情,那么看起来好多了。

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 . 在下面的代码示例中,使用StudentName类型的实例初始化Dictionary<TKey, TValue>

  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

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

            }; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM