Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Using Linq to get column from jagged array

How do I get elements of a column from a jagged array as a flat array using Linq ????

public class Matrix<T>
{
    private readonly T[][] _matrix;

    public Matrix(int rows, int cols)
    {
        _matrix = new T[rows][];
        for (int r = 0; r < rows; r++)
        {
            _matrix[r] = new T[cols];
        }
    }

    public T this[int x, int y]
    {
        get { return _matrix[x][y]; }
        set { _matrix[x][y] = value; }
    }

    // Given a column number return the elements
    public IEnumerable<T> this[int x]
    {
        get
        {
        }
    }
}

Matrix<double> matrix = new Matrix<double>(6,2);
matrix[0, 0] = 0;
matrix[0, 1] = 0;
matrix[1, 0] = 16.0;
matrix[1, 1] = 4.0;
matrix[2, 0] = 1.0;
matrix[2, 1] = 6.0;
matrix[3, 0] = 5.0;
matrix[3, 1] = 7.0;
matrix[4, 0] = 1.3;
matrix[4, 1] = 1.0;
matrix[5, 0] = 1.5;
matrix[5, 1] = 4.5;
like image 373
nixgadget Avatar asked Oct 12 '11 10:10

nixgadget


1 Answers

It's just:

public IEnumerable<T> this[int x]
{
    get
    {
       return _matrix.Select(row => row[x]);
    }
}

Of course it's better to check if x is not out of the range before the LINQ query.

Anyway, given that you're working on a matrix, for more clarity you could switch to a bidimensional array instead of a jagged array (so no doubt about the size of the 2 dimensions).

Instead, if performance really really matters for you, keep using jagged arrays which seem to be a bit faster than bidimensional arrays (e.g LINK1, LINK2).

like image 162
digEmAll Avatar answered Nov 15 '22 20:11

digEmAll