Proper way to initialize a C# dictionary with values?

前端 未结 6 1549
感情败类
感情败类 2020-11-29 15:49

I am creating a dictionary in a C# file with the following code:

private readonly Dictionary FILE_TYPE_DICT
        = new Dictiona         


        
相关标签:
6条回答
  • 2020-11-29 15:58

    With C# 6.0, you can create a dictionary in following way:

    var dict = new Dictionary<string, int>
    {
        ["one"] = 1,
        ["two"] = 2,
        ["three"] = 3
    };
    

    It even works with custom types.

    0 讨论(0)
  • 2020-11-29 15:59

    You can initialize a Dictionary (and other collections) inline. Each member is contained with braces:

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

    See MSDN for details.

    0 讨论(0)
  • 2020-11-29 16:05

    Suppose 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" }
    };
    
    0 讨论(0)
  • 2020-11-29 16:18

    I can't reproduce this issue in a simple .NET 4.0 console application:

    static class Program
    {
        static void Main(string[] args)
        {
            var myDict = new Dictionary<string, string>
            {
                { "key1", "value1" },
                { "key2", "value2" }
            };
    
            Console.ReadKey();
        }
    }
    

    Can you try to reproduce it in a simple Console application and go from there? It seems likely that you're targeting .NET 2.0 (which doesn't support it) or client profile framework, rather than a version of .NET that supports initialization syntax.

    0 讨论(0)
  • 2020-11-29 16:18

    Object initializers were introduced in C# 3.0, check which framework version you are targeting.

    Overview of C# 3.0

    0 讨论(0)
  • 2020-11-29 16:18

    With С# 6.0

    var myDict = new Dictionary<string, string>
    {
        ["Key1"] = "Value1",
        ["Key2"] = "Value2"
    };
    
    0 讨论(0)
提交回复
热议问题