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

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

问题描述

我尝试了以下操作,但它只返回一个搞砸的数组.

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;
    }

推荐答案

谢谢 Thomas,您的解释很有帮助,但您实施的解决方案太慢了.我修改了它以充分利用 Array.Copy.

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;
    }

这里我假设行数多于列数,因此我将数组构造为 [columns, rows].这样我就可以一次在整个列上使用 Array.Copy(一次比一个单元格快得多).

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天全站免登陆