How to insert values into C# Dictionary on instantiation?

后端 未结 8 1182
刺人心
刺人心 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:26

    You can also use Lambda expressions to insert any Key Value pairs from any other IEnumerable object. Key and value can be any type you want.

    Dictionary<int, string> newDictionary = 
                     SomeList.ToDictionary(k => k.ID, v => v.Name);
    

    I find that much simpler since you use the IEnumerable objects everywhere in .NET

    Hope that helps!!!

    Tad.

    0 讨论(0)
  • 2021-02-01 00:26

    Hope it will work perfectly.

    Dictionary<string, double> D =new Dictionary<string, double>(); D.Add("String", 17.00);

    0 讨论(0)
  • 2021-02-01 00:27

    You were almost there:

    var dict = new Dictionary<int, string>()
    { {0, "string"}, {1,"string2"},{2,"string3"}};
    
    0 讨论(0)
  • 2021-02-01 00:30
    Dictionary<int, string> dictionary = new Dictionary<int, string> { 
       { 0, "string" }, 
       { 1, "string2" }, 
       { 2, "string3" } };
    
    0 讨论(0)
  • 2021-02-01 00:30

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

    var dictionary = new Dictionary<int, string>
        {
            {0, "string"},
            {1, "string2"},
            {2, "string3"}
        };
    
    0 讨论(0)
  • 2021-02-01 00:33

    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}}
    };
    
    0 讨论(0)
提交回复
热议问题