2012-09-29 162 views
1

我从列表中创建了一个矩阵。我如何删除'i'列和'i'列?有没有一种方法呢?我试过RemoveAt,但是会删除一个项目。从列表中删除行和列c#

List<List<int>> mtx = new List<List<int>>(); 

    0 1 2 3 
    ------- 
0|0 0 0 0 
1|0 0 0 0 
2|0 0 0 0 
3|0 0 0 0 

比如我想删除行i = 2

+1

我建议使用数组而不是列表的列表来制作矩阵。 – podiluska

回答

1

你要做的它在2次。

首先删除第一维。 (我更喜欢谈论的尺寸比列/行可被误解)

mtx.removeAt(i); 

然后在第一维迭代,以消除第二维的元素。

foreach(List<int> list in mtx){ 
    list.removeAt(i); 
} 
1

要删除i行:

mtx.RemoveAt(i); 

删除列j

foreach (var row in mtx) 
{ 
    row.RemoveAt(j); 
} 
2

Cuong Le和Florian F.给出的答案是正确的;但我建议你创建一个矩阵类

public class Matrix : List<List<int>> 
{ 
    public void RemoveRow(int i) 
    { 
     RemoveAt(i); 
    } 

    public void RemoveColumn(int i) 
    { 
     foreach (List<int> row in this) { 
      row.RemoveAt(i); 
     } 
    } 

    public void Remove(int i, int j) 
    { 
     RemoveRow(i); 
     RemoveColumn(j); 
    } 

    // You can add other things like an indexer with two indexes 
    public int this[int i, int j] 
    { 
     get { return this[i][j]; } 
     set { this[i][j] = value; } 
    } 
} 

这使得使用矩阵更容易。更好的方法是隐藏实现(即,它不会在内部使用列表的矩阵类之外显示)。

public class Matrix 
{ 
    private List<List<int>> _internalMatrix; 

    public Matrix(int m, int n) 
    { 
     _internalMatrix = new List<List<int>(m); 
     for (int i = 0; i < m; i++) { 
      _internalMatrix[i] = new List<int>(n); 
      for (int j = 0; j < n; j++) { 
       _internalMatrix[i].Add(0); 
      } 
     } 
    } 

    ... 
} 

这使得您可以更轻松地在以后完成更改,例如,您可以通过数组替换列表,而不会损害矩阵的“用户”。

如果您有Matrix类,您甚至可以重载数学运算符以使用矩阵。请参阅本教程overloading operators