Panadol Chong
Panadol Chong

Reputation: 1903

how to declare a free length 2d array in c#

Good day,

Normally I create 2D array as follow :

string [,] arr = new string [9,4];

This is a 2D array with 9 rows and 4 columns.

I would like to ask, how to create 2D array with any length. For example, that is not nessecary to set the row to 9, it can be any number, depends on the situation.

Upvotes: 1

Views: 536

Answers (3)

Kaveh Shahbazian
Kaveh Shahbazian

Reputation: 13521

This Matrix class is space (based on access pattern) and performance efficient:

class Matrix<T>
{
    readonly Dictionary<int, Dictionary<int, T>> _rows = new Dictionary<int, Dictionary<int, T>>();

    public T this[int i, int j]
    {
        get
        {
            var row = ExpandOrGet(j);
            if (!row.ContainsKey(i)) row[i] = default(T);

            UpdateSize(i, j);

            return row[i];
        }
        set
        {
            ExpandOrGet(j);
            _rows[j][i] = value;

            UpdateSize(i, j);
        }
    }

    void UpdateSize(int i, int j)
    {
        if (j > SizeRows) SizeRows = j;
        if (i > SizeColums) SizeColums = i;
    }

    public int SizeRows { get; private set; }
    public int SizeColums { get; private set; }

    Dictionary<int, T> ExpandOrGet(int j)
    {
        Dictionary<int, T> result = null;

        if (!_rows.ContainsKey(j))
        {
            result = new Dictionary<int, T>();
            _rows[j] = result;
        }
        else result = _rows[j];

        return result;
    }
}

Although you can add further utilities to facilitate your workflow.

Upvotes: 0

Erik Schierboom
Erik Schierboom

Reputation: 16656

For that you must be using a List<List<string>> instance. Now you can dynamically add anything you want, however this also has the disadvantage over the array format that you need to check for yourself if you have reached the maximum number of rows or columns.

Upvotes: 2

Tigran
Tigran

Reputation: 62265

what about simple List<List<T>> ?

This is like a concept, you naturally can wrap up this in your custom class, so consumer of your API don't see these wiered nested declarations.

public class Matrix {

   private mtx = new List<List<T>>(); 


   public void Append(T value) {
      .....
   }  

   public void InsertAt(T value, int row, int column) {
      ....
   }

}

Upvotes: 4

Related Questions