0

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
1
  • You could try this, but I think a multidimensional array is not what you need, because if you care about the "pair" of words (like a table row), then it's an array of arrays, not single words scattered in a matrix. Commented Dec 3, 2021 at 21:35

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was aware of this approach but I was wondering if there was something different, maybe shorter? Thank you for your comment though appreciate the help nonetheless! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.