Search code examples
c#dynamic-data

Dynamic 2D structure for C#


I'm working on a class that is storing a 2D array of class MyType and would like it to use dynamic data types. i.e. not MyType[,]

The problem with MyType[,] is that the class doesn't know the size of the array ahead of time, and I don't want to go to the trouble of managing array re-sizing if it's been done elsewhere in the .NET Frameworks.

The class will not know maximum array size at any given moment, but the array will be dense. I know I can use static arrays, and re-allocate memory as needed, but I'd prefer to use a built-in implementation if possible.

Is there anything better than List<List<MyType>> for this purpose?

Edit 1: specified that array is dense;

Edit 2 and 3: specified problem with MyType[,]


Solution

  • Create your own List<List<T>> encapsulation like :

    public class Matrix<T>
    {
       List<List<T>> matrix;
    
       public void Add(IEnumerable<T> row)
       {
          List<T> newRow = new List<T>(row);
          matrix.Add(newRow);
       }
    
       public T this[int x, int y]
       {
          get  { return matrix[y][x]; }
       }
       ....
    }
    

    define your own set of operation on it ! Be freee !

    By encapsulating it, you can decide to go for a more optimised implementation later if it's not sufficient.

            ICollection<T> rowOne = (ICollection<T>)new List<Int64>();
            rowOne.Add(1);
            rowOneList.Add(2);
            rowOne.Add(3);
    
            ICollection<T> rowTwo = (ICollection<T>)new List<Int64>();
            rowTwo .Add(4);
            rowTwo .Add(5);
            rowTwo .Add(6);