C#列表清单问题

时间:2011-10-12 09:42:04

标签: c# arrays list

我对列表列表有另一个问题。再一次,我有如下的通用矩阵类。

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

// Test code
Matrix<double> matrix = new Matrix<double>();    
matrix.Add(new List<double>() { 0, 0 });
matrix.Add(new List<double>() { 16.0, 4.0 });

我正在从文本文件中读取字符串行,其中包含具有以下格式的值

4 2

0.5 0.4 0.6 0.1 10.1 11.1 0.5 12.0

第一行指定4x2矩阵大小。 第二行必须使得前4个值位于矩阵的第一列中,后4个值应位于第二列中。 这是动态的,因此尺寸不固定。

读取行并分隔这些行是有序的。我的问题是如何使用Matrix类来存储这些值。换句话说,我怎么能连续做元素?

应该这样做,矩阵看起来像,

0.5 10.1

0.4 11.1

0.6 0.5

0.1 12.0

提前致谢。

3 个答案:

答案 0 :(得分:1)

public void AddRange(IEnumerable<List<T>> rows)
{
    foreach (var row in rows)
    {
        Add(row);
    }
}

然后:

AddRange(new List<double>[] {
   new List<double> { 0.0, 0.0 },
   new List<double> { 16.0, 14.0 } });

答案 1 :(得分:1)

你的矩阵尺寸真的应该是可变的吗?一个更好的选择可能是在构造函数中传递其维度并在矩阵中分配数组

public class Matrix<T>
{
    private readonly T[][] _matrix;

    public Matrix(int rows, int cols)
    {
        _matrix = new T[rows][];
        for (int r = 0; r < rows; r++)
            _matrix[r] = new T[cols];
    }

    public T this[int r, int c]
    {
        get { return _matrix[r][c]; }
        set { _matrix[r][c] = value; }
    }
}

或者,它确实需要是可变的,你可以根据需要选择“懒惰”分配它:

public class Matrix<T>
{
    private readonly List<List<T>> _matrix;

    public Matrix()
    {
        _matrix = new List<List<T>>();
    }

    public T this[int r, int c]
    {
        get
        {
            ResizeIfNeeded(r, c);
            return _matrix[r][c]; 
        }
        set
        {
            ResizeIfNeeded(r, c);
            _matrix[r][c] = value;
        }
    }

    private void ResizeIfNeeded(int row, int col)
    {
        while (_matrix.Count <= r)
            _matrix.Add(new List<T>());

        var row = _matrix[r];
        while (row.Count <= c)
            row.Add(default(T));
    }
}

请注意,如果按顺序填充,第二种方法可能会进行大量分配。

我会选择第一种方法(固定大小的矩阵),因为在大多数情况下,它的尺寸已经知道。分配速度最快,在多线程应用程序中使用是安全的。

如果您正在从文件中读取值,则通过索引设置它们应该比为每行实例化一个新列表简单得多。

答案 2 :(得分:0)

所以你想要一个带有2个参数,宽度和值的ctor。

public Matrix(int width, IEnumerable<T> values)
{
    if (values.Count() % width != 0)
        throw new ArgumentException("values parameter is indivisible by width");

    int last = 0;
    for (int i = width; i <= values.Count(); i += width)
    {
        Add(values.Skip(last).Take(width))
        last = i;
    }

}