What is the easiest way to handle associative array in c#?

后端 未结 2 1463
星月不相逢
星月不相逢 2021-01-30 10:26

I do not have a lot of experience with C#, yet I am used of working with associative arrays in PHP.

I see that in C# the List class and the Array are available, but I wo

2条回答
  •  盖世英雄少女心
    2021-01-30 11:09

    A dictionary will work, but .NET has associative arrays built in. One instance is the NameValueCollection class (System.Collections.Specialized.NameValueCollection).

    A slight advantage over dictionary is that if you attempt to read a non-existent key, it returns null rather than throw an exception. Below are two ways to set values.

    NameValueCollection list = new NameValueCollection();
    list["key1"] = "value1";
    
    NameValueCollection list2 = new NameValueCollection()
    {
        { "key1", "value1" },
        { "key2", "value2" }
    };
    

提交回复
热议问题