开发者

What's the best way to implement an unfixed multi-deminsional array in C#.NET?

For example: an array of varying-length arrays of integers.

In C++, we are used to doing things like:

int * * TwoDimAry = new int * [n] ;

for ( int i ( 0 ) ; i < n ; i ++ )
{
    TwoDimAry[i] = new int [i + n] ;
}

In this case, if n == 3 then the result would be an开发者_Python百科 array of three pointers to arrays of integers, and would appear like this:

http://img263.imageshack.us/img263/4149/multidimarray.png

Of course, .NET arrays are managed collections, so you don't have to deal with the manual allocation/deletion.

But declaring:

int[][] TwoDimAry ;

... in C# does not appear to have the same effect - namely, you have to innitialize ALL of the sub-arrays at the same time, and they have to be the same length.

I need my sub-arrays to be independent of each-other, as they are in native C++.

What's the best way to implement this using managed collections? Are there any drawbacks I should be aware of?


Like C++, you need to initialize every subarray in an int[][].

However, they don't need to have the same length. (That's why it's called a jagged array)

For example:

int[][] jagged1 = new int[][] { new int[1], new int[2], new int[3] };

Your C++ code can be translated directly to C#:

int[][] TwoDimAry = new int[n][];

for(int i = 0; i < n; i++) {
    TwoDimAry[i] = new int[i + n];
}


Here is an example with a jagged array initialized with 1, 2, 3, .. elements for each row

int N = 20;
int[][] array = new int[N][];      // First index is rows, second is columns
for(int i=0; i < N; i++)
{
    array[i] = new int[i+1];       // Initialize i-th row with 'i' columns
    for( int j = 0; j <= i; j++)
    {
         array[i][j] = N*j+i;      // Set a value for each column in the row
    }
}

I have use this enough to know that there aren't many drawbacks overall. Hybrid appraches with List<int[]> or List<int>[] also work.


In .Net, most of the time you don't want to use arrays this way at all. This is because in .Net, arrays are thought of as a different animal from a collection. Managed, yes. Collection? Well, maybe, but it confuses terms because that means something special. If you want a collection (hint: most of the time you do), look in the Systems.Collections namespace, particularly Systems.Collections.Generic. It sounds like you really want either a List<List<int>> or a List<int[]>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜