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

送分小仙女□ 提交于 2019-12-20 08:24:11

问题


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 would like to associate some string keys.

What is the easiest way to handle this?

Thx!


回答1:


Use the Dictionary class. It should do what you need. Reference is here.

So you can do something like this:

IDictionary<string, int> dict = new Dictionary<string, int>();
dict["red"] = 10;
dict["blue"] = 20;



回答2:


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" }
};


来源:https://stackoverflow.com/questions/10250232/what-is-the-easiest-way-to-handle-associative-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!