c#列表的列表(2D矩阵)

本文关键字:列表 矩阵 2D | 更新日期: 2023-09-27 18:11:14

我试图实现一个2D数组类使用列表的列表。有人能帮我实现一个类似于T的get函数这个[int x, int y]下面的函数,以获得由[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]; }
    }
}

c#列表的列表(2D矩阵)

由于您想要返回的每个值都在单独的行中,因此在单独的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];            
    }
}

yield比实例化结果数组有一些好处,因为它可以更好地控制输出的使用方式。例如,myMatrix[1].ToArray()会给你一个双精度[],而myMatrix[1].Take(5).ToArray()只会实例化一个双精度[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;
        }
    }