user1708689
user1708689

Reputation: 13

removing row and column from a List of a List c#

I made a matrix from list of list. How can I remove column 'i' and row 'i'? Is there a method for that? I've tried RemoveAt but that'd remove one item.

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

For example I would like to delete row i=2

Upvotes: 1

Views: 6546

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112344

The answers given by Cuong Le and Florian F. are correct; however I would suggest you to create a Matrix class

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

This makes it easier to work with matrices. An even better way would be to hide the implementation (i.e., it would not be visible outside the matrix class that you are using lists internally).

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

    ...
}

This makes it easier for you to change the implementation completely later, e.g. you could replace the lists by arrays, without impairing the "users" of the matrix.

You can even overload the mathematical operators to work with matrices, if you have a Matrix class. See this tutorial on overloading operators.

Upvotes: 3

cuongle
cuongle

Reputation: 75306

To delete row i:

mtx.RemoveAt(i);

to delete column j:

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

Upvotes: 1

Florian F.
Florian F.

Reputation: 4700

You have to do it in 2 times.

First remove the 1st dimension. (I like better to talk about dimensions than columns/rows which can be misinterpreted)

mtx.removeAt(i);

Then iterate over 1st dimension to remove your element on 2nd dimension.

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

Upvotes: 1

Related Questions