我从列表的列表中创建了一个矩阵。如何删除“i”列和“i”行?有办法吗?我试过 RemoveAt 但这会删除一项。
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
请您参考如下方法:
Cuong Le 和 Florian F. 给出的答案是正确的;但是我建议你创建一个 Matrix 类
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 上的本教程.
