[英]Mapping from 2D array in C#
我想在C#中使用二維數組,例如:
string[,] a = new string[,]
{
{"aunt", "AUNT_ID"},
{"Sam", "AUNT_NAME"},
{"clozapine", "OPTION"},
};
我的要求是,當我將"aunt"
傳遞給該數組時,我想從二維數組中獲取相應的AUNT_ID
。
就像其他人所說的那樣, Dictionary<string, string>
會更好-您可以使用集合初始值設定項來簡單地創建它:
Dictionary<string, string> dictionary = new Dictionary<string, string>
{
{"ant", "AUNT_ID"},
{"Sam", "AUNT_NAME"},
{"clozapine", "OPTION"},
};
如果您確信自己的鑰匙在字典中,並且很高興在其他情況下拋出異常:
string value = dictionary[key];
或者可能不是:
string value;
if (dictionary.TryGetValue(key, out value))
{
// Use value here
}
else
{
// Key wasn't in dictionary
}
如果確實需要使用數組,可以將其更改為多維數組( string[][]
),則可以使用:
// Will throw if there are no matches
var value = array.First(x => x[0] == key)[1];
還是再次謹慎一點:
var pair = array.FirstOrDefault(x => x[0] == key);
if (pair != null)
{
string value = pair[1];
// Use value here
}
else
{
// Key wasn't in dictionary
}
不幸的是,LINQ在矩形陣列上不能很好地工作。 坦率地說,編寫一種方法可以使它像數組的數組一樣被“某種程度上”對待並不難。
為此使用Dictionary<string, string>
:
Dictionary<string, string> arr = new Dictionary<string, string>();
arr.Add("ant", "AUNT_ID");
arr.Add("Sam", "AUNT_NAME");
arr.Add("clozapine", "OPTION");
string k = arr["ant"]; // "AUNT_ID"
最好的選擇是使用Dictionary,但是如果您仍然想使用2D數組,則可以嘗試以下方法
string[,] a = new string[,]
{
{"ant", "AUNT_ID"},
{"Sam", "AUNT_NAME"},
{"clozapine", "OPTION"},
};
string search = "ant";
string result = String.Empty;
for (int i = 0; i < a.GetLength(0); i++) //loop until the row limit
{
if (a[i, 0] == search)
{
result = a[i, 1];
break; //break the loop on find
}
}
Console.WriteLine(result); // this will display AUNT_ID
您似乎想要一本字典:
Dictionary<string, string> a = new Dictionary<string, string>();
a.Add("ant", "AUNT_ID");
a.Add("Sam", "AUNT_NAME");
a.Add("clozapine", "OPTION");
string s = a["ant"]; // gets "AUNT_ID"
要檢查字典中是否存在鍵:
if (a.ContainsKey("ant")) {
...
}
要么:
string s;
if (a.TryGetValue("ant", out s)) {
...
}
for (i=0; i<3; i++){
if (!String.Compare(a[i][0], string)){
stored_string= a[i][1];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.