簡體   English   中英

C#清單清單(2D矩陣)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM