简体   繁体   中英

Initiate collection in c# similar to Java anonymous class syntax

In Java we can initialize an ArrayList and HashMap with anonymous class declaration syntax as follows

public static final List<HashMap<String,String>> data
 = new ArrayList<HashMap<String,String>>(){
{
 add(
  new HashMap<String, String>()
    {{ 
      put("name", "My Name");
      put("alias", "My Name");
    }}
  );
};

Can we do the same in C#? in latest windows 10 programming?

Collection initialization is also a feature of C#. The syntax to initiate a collection in C# 4.0 is similar to that you have shown.

private static List<Dictionary<string, string>> data = 
    new List<Dictionary<string,string>>()
    {

        new Dictionary<string, string>()
            {
                { "name", "My Name" },
                {"alias", "My Name" }
            },
        new Dictionary<string, string>()
            {
                { "name2", "My Name2" },
                {"alias2", "My Name2" }
            }   
    };

For more, please consult the feature's documentation . ( Click here for the documentation specific to C# 4.0/Visual Studio 2010.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM