这是一个不破坏数据结构的示例:
static int IndexOf<T>(T[,] array, T toFind)
{
int i = -1;
foreach (T item in array)
{
++i;
if (toFind.Equals(item))
break ;
}
return i;
}
static string GetRandomString(string[,] array, string toFind)
{
int lineLengh = array.Length / array.Rank;
int index = IndexOf(array, toFind);
int lineIndex = index / lineLengh;
Random random = new Random();
index = random.Next(lineIndex * lineLengh + 1, (lineIndex + 1) * lineLengh);
return array[lineIndex, index % lineLengh];
}
// If you want to get a random element between the index and the end of the line
// You can replace "bird" by any word you want,
// except a word at the end of a line (it will return you the first element of the next line)
// static string GetRandomString(string[,] array, string toFind)
// {
// int lineLengh = array.Length / array.Rank;
// int index = IndexOf(array, toFind);
// Random random = new Random();
// index = random.Next(index + 1, (index / lineLengh + 1) * lineLengh);
// return array[index / lineLengh, index % lineLengh];
// }
static void Main(string[] args)
{
string[,] array = new string[,]
{
{"cat", "dog", "plane"},
{"bird", "fish", "elephant"},
};
Console.WriteLine(GetRandomString(array, "bird"));
Console.ReadKey();
}
为了完美,您应该添加一个检查索引是否不是-1,以及是否可以从索引和行尾之间的范围内获取随机数。
如果您的多维数组可以包含不同大小的行,您还应该使用 string[][]。使用 string[,],您的数组必须包含相同大小的行。