2

I'm fairly new with C# and having trouble converting some array types.

JavaScript code:

function toMatrix(list, elementsPerSubArray) {
    var matrix = [], i, k;
    for (i = 0, k = -1; i < list.length; i++) {
        if (i % elementsPerSubArray === 0) {
            k++;
            matrix[k] = [];
        }
        matrix[k].push(list[i]);
    }
    return matrix;
}

I have tried converting the code but I struggle with the arrays in C#.

This may be easy to some, how would I do this?

Thanks.

0

2 Answers 2

3

Here is an attempt. I used a generic parameter for the item type:

List<List<T>> toMatrix<T>(List<T> list, int elementsPerSubArray) 
{
    var matrix = new List<List<T>>();
    int k = -1;
    for (int i = 0 ; i < list.Length; i++) 
    {
        if (i % elementsPerSubArray == 0) 
        {
            k++;
            matrix.Add(new List<T>());
        }
        matrix[k].Add(list[i]);
    }
    return matrix;
}

Test:

List<int> input = new List<int> { 1, 2, 3, 4, 5, };
var result = toMatrix(input, 2);
    foreach (var outer in result)
        Console.WriteLine(string.Join(", ", outer));

(Demo on Ideone)

Sign up to request clarification or add additional context in comments.

1 Comment

matrix.Aggregate(new T[0], (array, matrixRow) => array.Concat(matrixRow).ToArray());. This is why I love Linq: it's a glimpse into a functional programming view of the world, implemented in what was originally an object-oriented language.
0

A Linq version would look like this.

using System.Linq;
using System.Collections.Generic;

public T[][] ToMatrix<T>(T[] array, int elementsPerSubArray)
{
    var list = new List<T[]>();
    while (array.Any())
    {
        list.Add(array.Take(elementsPerSubArray).ToArray());
        array = array.Skip(elementsPerSubArray).ToArray();
    }
    return list.ToArray();
}

Converting back can be achieved in one line:

public T[] ToArray<T>(T[][] matrix)
{
    return matrix.Aggregate(new T[0], (array, matrixRow) => array.Concat(matrixRow).ToArray());
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.