使用 C# 在多维数组中搜索特定值

Searching for specific values in multidimensional array using C#

我有一个长度未知的多维字符串数组,其中包含以下数据:

string[,] phrases = new string[,] { { "hello", "world" }, { "hello2", "world2" } };

我正在尝试搜索数组以按照数组中的顺序查找这两个词。

请问是否存在类似下面的内容?

Console.WriteLine(Array.Exists(phrases, {"hello", "world"})); // Result should be True
Console.WriteLine(Array.Exists(phrases, {"hello", "hello2"})); // Result should be False

您可以使用 LINQ 从“短语”中提取每一行,然后使用 Enumerable.SequenceEqual():

将该行与您的目标进行比较
static void Main(string[] args)
{
    string[,] phrases = new string[,] { { "hello", "world" }, { "hello2", "world2" } };

    Console.WriteLine(ArrayExists(phrases, new string[] { "hello", "world"}));
    Console.WriteLine(ArrayExists(phrases, new string[] { "hello", "hello2"}));

    Console.WriteLine("Press Enter to Quit...");
    Console.ReadLine();
}

public static bool ArrayExists(string[,] phrases, string[] phrase)
{
    for(int r=0; r<phrases.GetLength(0); r++)
    {
        string[] row = Enumerable.Range(0, phrases.GetLength(1)).Select(c => phrases[r, c]).ToArray();
        if (row.SequenceEqual(phrase))
        {
            return true;
        }
    }
    return false;
}