开发者

C# List of lists (2D matrix)

开发者 https://www.devze.com 2023-04-12 15:55 出处:网络
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 g

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;
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号