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

C#Associative Array

C# Problem Overview


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!

C# Solutions


Solution 1 - C#

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;

Solution 2 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichaelView Question on Stackoverflow
Solution 1 - C#dcpView Answer on Stackoverflow
Solution 2 - C#DAGView Answer on Stackoverflow