从C#中的2D数组映射

时间:2012-05-29 05:18:32

标签: c# arrays

我想在C#中使用二维数组,例如:

string[,] a = new string[,]
{
    {"aunt", "AUNT_ID"},
    {"Sam", "AUNT_NAME"},
    {"clozapine", "OPTION"},
};

我的要求是,当我将"aunt"传递给此数组时,我希望从二维数组中获得相应的AUNT_ID

5 个答案:

答案 0 :(得分:4)

正如其他人所说,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对矩形阵列的效果不佳。编写一个方法可能不会太难以让它像某个数组一样“有点”对待,不可否认......

答案 1 :(得分:2)

使用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"

答案 2 :(得分:1)

最好的选择是使用词典,但如果您仍想使用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

答案 3 :(得分:0)

看起来你想要一本字典:

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)) {
  ...
}

答案 4 :(得分:-2)

for (i=0; i<3; i++){
    if (!String.Compare(a[i][0], string)){
        stored_string= a[i][1];
    }
}