开发者

How to create an array with label and not integer

开发者 https://www.devze.com 2023-03-13 06:22 出处:网络
Suppose I have an array of strings like : myArray[\"hello\", \"my\", \"na开发者_Python百科me\", \"is\", \"marco\"]

Suppose I have an array of strings like :

myArray["hello", "my", "na开发者_Python百科me", "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


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


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号