我想在 C# 中使用二维数组,例如:
string[,] a = new string[,]
{
{"aunt", "AUNT_ID"},
{"Sam", "AUNT_NAME"},
{"clozapine", "OPTION"},
};
我的要求是,当我传递"aunt"
给这个数组时,我想AUNT_ID
从二维数组中得到对应的值。
正如其他人所说, aDictionary<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];
}
}