2011-06-16 72 views
1

假設我有一個字符串像數組:如何創建帶有標籤的數組,而不是整數

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

訪問這個變量,我不得不把整數作爲指標。所以,如果我想要提取第三個元素,我只是做:

myArray[2] 

現在,我想使用標籤,而不是整數。 因此,例如像出頭:

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

我如何能做到這一點的C#?可能嗎?謝謝

回答

9

這就是所謂的關聯數組,而C#不直接支持它們。但是,您可以使用Dictionary<TKey, TValue>實現完全相同的效果。您可以使用Add方法(如果您嘗試添加一個已存在的鍵會引發異常)或直接使用索引器(如果您使用相同的鍵兩次覆蓋現有值)來添加值。

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

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

您正在查找關聯數組,我認爲this question是您正在查找的內容。

1

C#有一個Dictionary類(和接口)來處理這種存儲。例如:

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

下面是文檔:http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

1

隨着你就可以設置每個項目作爲一個字符串的「鑰匙」,並給他們的字符串「值」的字典。例如:

Dictionary<string, string> dic = new Dictionary<string, string>(); 
dic.Add("canada", "hello"); 
相關問題