How to insert values into C# Dictionary on instant

2020-05-18 04:33发布

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 if there is something more efficient like:

Dictionary<int, string>(){(0, "string"),(1,"string2"),(2,"string3")};

标签: c# dictionary
8条回答
劳资没心,怎么记你
2楼-- · 2020-05-18 04:41
Dictionary<int, string> dictionary = new Dictionary<int, string> { 
   { 0, "string" }, 
   { 1, "string2" }, 
   { 2, "string3" } };
查看更多
狗以群分
3楼-- · 2020-05-18 04:42

You can instantiate a dictionary and add items into it like this:

var dictionary = new Dictionary<int, string>
    {
        {0, "string"},
        {1, "string2"},
        {2, "string3"}
    };
查看更多
该账号已被封号
4楼-- · 2020-05-18 04:45

There's whole page about how to do that here:

http://msdn.microsoft.com/en-us/library/bb531208.aspx

Example:

In the following code example, a Dictionary<TKey, TValue> is initialized with instances of type StudentName:

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}}
};
查看更多
做个烂人
5楼-- · 2020-05-18 04:51

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"];
}
查看更多
劫难
6楼-- · 2020-05-18 04:52

You were almost there:

var dict = new Dictionary<int, string>()
{ {0, "string"}, {1,"string2"},{2,"string3"}};
查看更多
Emotional °昔
7楼-- · 2020-05-18 04:57

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

查看更多
登录 后发表回答