Home > Software engineering >  Convert multi-dimensional array to multi-dimensional dictionary
Convert multi-dimensional array to multi-dimensional dictionary

Time:12-03

How do I convert a multi-dimensional array of int into a multi-dimensional dictionary using Lambda?

For example I would like to convert Test1 (int[2,3]) into Test 3 (Dictionary<(int,int),int>)

    int[,] Test1 = new int[2, 3];
    int k = 0;
    for (int i = 0; i < 2; i  )
    {
        for (int j = 0; j < 3; j  )
        {
            Test1[i, j] = k  ;
        }
    }

I can easily convert it into dictionary using the traditional way with the "for - next" loop but when I tried using lambda:

Dictionary<(int,int),int>Test3 = Enumerable.Range(0, Test1.Length)
    .ToDictionary((int i ,int j )=>new { z =Test1[i, j] });

I got the syntax error below:

Error   CS0411  The type arguments for method 'Enumerable.ToDictionary<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

How do I specify the type arguments explicitly?

CodePudding user response:

Unfortunately you can't easily use Linq to loop through "rows" of a 2-D array, since the iterator for a square array just loops through the elements. You'll need to use an old-fashion for loop:

var Test3 = new Dictionary<(int,int),int>();

for (int i = 0; i < Test1.GetLength(0); i  )
{
    Test3[(Test1[i, 0], Test1[i, 1])] =  Test1[i, 2];
}

This assumes that the pairs in the first two "columns" are unique, otherwise the last one would "win".

You could use Linq to enumerate through the rows by usinng Range over one axis as you tried to do:

Dictionary<(int,int),int>Test3 = Enumerable
    .Range(0, Test1.GetLength(0))
    .ToDictionary(i => (Test1[i, 0], Test1[i, 1]), i => Test1[i, 2]);

Note that the lambdas in ToDictionary define the key and value, respectively.

but the for loop is cleaner and easier to understand in my opinion.

  • Related