Can I use a collection initializer for Dictionary entries?

前端 未结 7 1385
猫巷女王i
猫巷女王i 2020-12-09 14:19

I want to use a collection initializer for the next bit of code:

public Dictionary GetNames()
{
    Dictionary names =          


        
7条回答
  •  盖世英雄少女心
    2020-12-09 14:58

    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
    {
       [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
    {
       { 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
    {
       [1] = "Adam",
       [2] = "Bart",
       [3] = "Charlie",
    };
    

提交回复
热议问题