简体   繁体   中英

2d Data Structure in C#

我正在寻找可以帮助我确定在使用 C# 创建二维数据结构时使用哪种方法的资源。

Do you mean multidimensional array? It's simple:

<type>[,] <name> = new <type>[<first dimenison>,<second dimension>];

Here is MSDN reference:

Multidimensional Arrays (C#)

@Traumapony-- I'd actually state that the real performance gain is made in one giant flat array, but that may just be my C++ image processing roots showing.

It depends on what you need the 2D structure to do. If it's storing something where each set of items in the second dimension is the same size, then you want to use something like a large 1D array, because the seek times are faster and the data management is easier. Like:

for (y = 0; y < ysize; y++){
   for (x = 0; x < xsize; x++){
      theArray[y*xsize + x] = //some stuff!
   }
}

And then you can do operations which ignore neighboring pixels with a single passthrough:

totalsize = xsize*ysize;
for (x = 0; x < totalsize; x++){
   theArray[x] = //some stuff!
}

Except that in C# you probably want to actually call a C++ library to do this kind of processing; C++ tends to be faster for this, especially if you use the intel compiler.

If you have the second dimension having multiple different sizes, then nothing I said applies, and you should look at some of the other solutions. You really need to know what your functional requirements are in order to be able to answer the question.

Depending on the type of the data, you could look at using a straight 2 dimensional array:

int[][] intGrid;

If you need to get tricky, you could always go the generics approach:

Dictionary<KeyValuePair<int,int>,string>;

That allows you to put complex types in the value part of the dictionary, although makes indexing into the elements more difficult.

If you're looking to store spatial 2d point data, System.Drawing has a lot of support for points in 2d space.

Data Structures in C#

Seriously, I'm not trying to be critical of the question, but I got tons of useful results right at the top of my search when I Googled for:

data structures c#

If you have specific questions about specific data structures, we might have more specific answers...

For performance, it's best not to use multi-dimensional arrays ([,]); instead, use jagged arrays. eg:

<type>[][] <name> = new <type>[<first dimension>];
for (int i = 0; i < <first dimension>; i++)
{
    <name>[i] = new <type>[<second dimension>];
}

To access:

<type> item = <name>[<first index>][<second index>];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM