[英]C# List of lists (2D matrix)
我正在尝试使用列表列表实现2D数组类。 有人可以帮我实现一个类似于下面的T this [int x,int y]函数的get函数,以获取[int x ,:]给定的列中的所有元素,其中x是该列。 作为数组返回就可以了。
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]; }
}
}
由于要返回的每个值都在单独的行中,因此在单独的List
,您必须遍历所有行列表并返回这些行的元素x
。
返回的值数将始终等于行数,因此您可以:
T[] columnValues = new T[matrix.Count];
for (int i = 0; i < matrix.Count; i++)
{
columnValues[i] = matrix[i][x];
}
return columnValues;
或者:返回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具有一些好处,因为它可以更好地控制输出的使用方式。 例如,myMatrix [1] .ToArray()会给你double [],而myMatrix [1] .Take(5).ToArray()只会实例化double [5]
您必须确保每个矩阵列表至少包含x个元素
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.