Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Parallel.ForEach with a multidimensional array

I'm having a little trouble figuring out how to call the Parallel.ForEach with a 2D array of strings:

string[,] board = new string[,]{
        {"A", "B", "C", "D", "E" },
        {"F", "G", "H", "I", "J"},
        {"K", "L", "M", "N", "O"},
        {"0", "1", "2", "3", "4"}};

Parallel.ForEach(board, row =>
    {
        for (int i = 0; i < row.Length; ++i)
        {
            // find all valid sequences
        }
    });

If I don't specify the type explicitly I get the following error:

The type arguments for method 'System.Threading.Tasks.Parallel.ForEach(System.Collections.Generic.IEnumerable, System.Action)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

What's the proper way to specify the type arguments explicitly?

like image 653
Kiril Avatar asked Jan 21 '23 17:01

Kiril


1 Answers

The problem for you is that 2-dimensional arrays do not implement IEnumerable<one-dimensional-array>. (It does implement IEnumerable, but it's an IEnumerable of strings that "flattens" the array.) You can do two things:

  • Change the string[,] to a jagged array-of-arrays, string[][].

  • Implement your own extension method that iterates over a two-dimensional array and turns it into an IEnumerable<one-dimensional-array>.

like image 148
mqp Avatar answered Jan 29 '23 23:01

mqp