1

Suppose I have an array of strings like :

myArray["hello", "my", "name", "is", "marco"]

to access to this variable, I have to put an integer as index. So if I wanto to extract the third element I just do :

myArray[2]

Now, I'd like to use label instead of integer. So for example somethings like :

myArray["canada"]="hello";
myArray["america"]="my";
myArray["brazil"]="name";
myArray["gosaldo"]="is";
myArray["italy"]="marco";

How can I do this on C#? Is it possible? Thanks

markzzz
  • 47,390
  • 120
  • 299
  • 507

4 Answers4

9

That's called an associative array, and C# doesn't support them directly. However, you can achieve exactly the same the effect with a Dictionary<TKey, TValue>. You can add values with the Add method (which will throw an exception if you try to add an already existing key), or with the indexer directly, as below (this will overwrite the existing value if you use the same key twice).

Dictionary<string, string> dict = new Dictionary<string, string>();

dict["canada"] = "hello";
dict["america"] = "my";
dict["brazil"] = "name";
dict["gosaldo"] = "is";
dict["italy"] = "marco";
Sven
  • 21,903
  • 4
  • 56
  • 63
1

C# has a Dictionary class (and interface) to deal with this sort of storage. For example:

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("canada", "hello");
dict.Add("america", "my");
dict.Add("brazil", "name");
dict.Add("gosaldo", "is");

Here are the docs: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

Tom Hazel
  • 3,232
  • 2
  • 20
  • 20
1

With a Dictionary you will be able to set the "key" for each item as a string, and and give them string "values". For example:

Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("canada", "hello");
carlbenson
  • 3,177
  • 5
  • 35
  • 54
0

You're looking for an associative array and I think this question is what you're looking for.

Community
  • 1
  • 1
m.edmondson
  • 30,382
  • 27
  • 123
  • 206