Im trying to implement a 2D array class using List of Lists. Can someone please help me to implement a get function similar to T this[int x, int y] function below to get all the elements in a column given by [int x,:] where x is the column. Returning as an array would be fine.
public class Matrix<T>
{
List<List<T>> matrix;
public Matrix()
{
matrix = new List<List<T>>();
}
public void Add(IEnumerable<T> row)
{
List<T> newRow = new List<T>(row);
matrix.Add(newRow);
}
public T this[int x, int y]
{
get { return matrix[y][x]; }
}
}开发者_Go百科
Since each value you want to return is in a separate row, and so in a separate List
, you'll have to iterate through all row lists and return element x
of those rows.
The number of values returned will always equal the number of rows, so you could:
T[] columnValues = new T[matrix.Count];
for (int i = 0; i < matrix.Count; i++)
{
columnValues[i] = matrix[i][x];
}
return columnValues;
Or: return matrix.Select(z=>z.ElementAtOrDefault(x));
public IEnumerable<T> this[int x]
{
get
{
for(int y=0; y<matrix.Count; y++)
yield return matrix[y][x];
}
}
Yielding has some benefits over instantiating a result array as it gives better control over how the output is used. E.g. myMatrix[1].ToArray() will give you a double[] whereas myMatrix[1].Take(5).ToArray() will only instantiate a double[5]
you have to make sure that every lists of matrix have at least x elements
public T[] this[int x]
{
get
{
T[] result = new T[matrix.Count];
for (int y = 0; y < matrix.Count; y++)
{
result[y] = matrix[y][x];
}
return result;
}
}
精彩评论