Can I use a collection initializer for Dictionary entries?

前端 未结 7 1329
猫巷女王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 15:11

    Yes we can use collection initializer in dictionary.If 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)
提交回复
热议问题