如何调整在C#中的多维(2D)阵列? [英] How to resize multidimensional (2D) array in C#?

查看:81
本文介绍了如何调整在C#中的多维(2D)阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过以下,但它只是返回一个搞砸了数组。

  T [,] ResizeArray< T>(T [,]原来,诠释行,诠释COLS)
    {
        VAR newArray =新的T [行,COLS]
        Array.Copy(原件,newArray,original.Length);
        返回newArray;
    }


解决方案

感谢您托马斯,你的解释是非常有益的,但​​你的解决方案实现的速度太慢。我修改了它把Array.Copy很好的利用。

 无效ResizeArray< T>(REF T [,]原来,INT newCoNum,诠释newRoNum)
    {
        VAR newArray =新的T [newCoNum,newRoNum]
        INT列数= original.GetLength(1);
        INT columnCount2 = newRoNum;
        诠释列= original.GetUpperBound(0);
        对于(INT共同= 0; CO< =列;共++)
            Array.Copy(原件,合作*列数,newArray,合作* columnCount2,列数);
        原来= newArray;
    }

在这里,我假设有比列的多个行,所以我构造的数组[列,行]。这样,我在一杆(速度远远超过一个单元时)使用Array.Copy上一整列。

它只能递增数组的大小,但它也许可以进行调整,以减少大小了。

I tried the following but it just returns a screwed up array.

    T[,] ResizeArray<T>(T[,] original, int rows, int cols)
    {
        var newArray = new T[rows,cols];
        Array.Copy(original, newArray, original.Length);
        return newArray;
    }

解决方案

Thank you Thomas, your explanation was very helpful but your implemented solution is too slow. I modified it to put Array.Copy to good use.

    void ResizeArray<T>(ref T[,] original, int newCoNum, int newRoNum)
    {
        var newArray = new T[newCoNum,newRoNum];
        int columnCount = original.GetLength(1);
        int columnCount2 = newRoNum;
        int columns = original.GetUpperBound(0);
        for (int co = 0; co <= columns; co++)
            Array.Copy(original, co * columnCount, newArray, co * columnCount2, columnCount);
        original = newArray;
    }

Here I'm assuming that there are more rows than columns so I structured the array as [columns, rows]. That way I use Array.Copy on an entire column in one shot (much faster than one cell a time).

It only works to increment the size of the array but it can probably be tweaked to reduce the size too.

这篇关于如何调整在C#中的多维(2D)阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆