How to insert values into C# Dictionary on instantiation?

后端 未结 8 1184
刺人心
刺人心 2021-02-01 00:12

Does anyone know if there is a way I can insert values into a C# Dictionary when I create it? I can, but don\'t want to, do dict.Add(int, \"string\") for each item

相关标签:
8条回答
  • 2021-02-01 00:36

    Just so you know as of C# 6 you can now initialize it as follows

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

    Much cleaner :)

    0 讨论(0)
  • This isn't generally recommended but in times of uncertain crises you can use

    Dictionary<string, object> jsonMock = new Dictionary<string, object>() { { "object a", objA }, { "object b", objB } };
    
    // example of unserializing
    ClassForObjectA anotherObjA = null;
    if(jsonMock.Contains("object a")) {
        anotherObjA = (ClassForObjA)jsonMock["object a"];
    }
    
    0 讨论(0)
提交回复
热议问题