Student
Student

Reputation: 124

Searching for specific values in multidimensional array using C#

I have a multidimensional string array of unknown length with the following data:

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

I am trying to search through the array to find both words in the order that they are in the array.

Does something like the following exist please?

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

Upvotes: 0

Views: 133

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39122

You can extract each row from "phrases" using LINQ, then compare that row with your target using 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;
}

Upvotes: 1

Related Questions