I want to use a 2-D array in C#, e.g:
string[,] a = new string[,]
{
{"aunt", "AUNT_ID"},
{"Sam", "AUNT_NAME"},
{"clozapine", "OPTION"},
};
My requirement is that when I pass "aunt" to this array I want to get corresponding AUNT_ID from the 2-D array.
As others have said, a
Dictionary<string, string>would be better – and you can use a collection initializer to create it simply:If you’re confident that your key is in the dictionary, and you’re happy for an exception to be thrown otherwise:
or if it might not be:
If you really need to use an array, if you can change it to a multidimensional array (
string[][]), you can use:Or again to be more circumspect:
LINQ unfortunately doesn’t work quite as well on rectangular arrays. It probably wouldn’t be too hard to write a method to allow it to be treated “somewhat” like an array of arrays, admittedly…