C # Using Linq to get a column from an uneven array

How to get column elements 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; 
+6
source share
3 answers

It's simple:

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

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

In any case, given that you are working on a matrix, for clarity, you can switch to a two-dimensional array instead of an array with a serrated contour (so do not doubt the size of the two dimensions).

Instead, if performance is really important to you, keep using jagged arrays that seem a little faster than two-dimensional arrays (like LINK1 , LINK2 ).

+11
source
 var source = new int[3][] { Enumerable.Range(1,3).ToArray(), Enumerable.Range(10,5).ToArray(), Enumerable.Range(100,10).ToArray() }; int index = 0; var result = (from array in source from item in array group item by Array.IndexOf(array, item) into g where g.Key == index select g.ToArray()).FirstOrDefault(); 
+1
source
 var q = from row in jagged from value in row where value == anyvalue select value; 

Anyway, why do you want to use LINQ? using the classic one for it will improve performance and simplify debugging

0
source

Source: https://habr.com/ru/post/899122/


All Articles