C#转换一维数组为2D [英] C# convert 1D array to 2D

查看:104
本文介绍了C#转换一维数组为2D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己转换1D字节数组单通过执行以下操作,以2D的。我怀疑这可能是一样快,其他的方法,但也许有一个更清洁更简单的模式? (LINQ?)

 私有静态的byte [,] byte2D(字节[]输入,INT的高度,诠释宽度)
{
字节[,] =输出新的字节[高度,宽度]
的for(int i = 0; I<高度;我++)
{
为(INT J = 0; J<宽度; J ++)
{
输出[I,J] =输入[我*宽+ J]。
}
}
返回输出;
}

私有静态单[,] single2D(字节[]输入,INT的高度,诠释宽度)
{
单[,]输出=新单[高度宽度];
的for(int i = 0; I<高度;我++)
{
为(INT J = 0; J<宽度; J ++)
{
输出[I,J] =(单人间)输入[我*宽+ J]。
}
}
返回输出;
}


解决方案

这不利于使得清洁方法里面的代码,但我注意到,你有2只在他们的类型不同,基本相同的方法。我建议使用仿制药的。



这将让你定义只有一次你的方法。使用 ,其中 关键字,你甚至可以限制你允许你的方法去努力的那种类型。

 私有静态T [,] Make2DArray< T>(T []输入,INT的高度,诠释宽度)
{
T [,] =输出新的T [高度,宽度]
的for(int i = 0; I<高度;我++)
{
为(INT J = 0; J<宽度; J ++)
{
输出[I,J] =输入[我*宽+ J]。
}
}
返回输出;
}

您会调用此方法像这样

  INT []一个; //或任何其它阵列。 
变种twoDArray = Make2DArray(一,高度,宽度);


I find myself converting 1D byte and single arrays to 2D by doing the following. I suspect it is probably as fast as other methods, but perhaps there is a cleaner simpler paradigm? (Linq?)

    private static byte[,] byte2D(byte[] input, int height, int width)
    {
        byte[,] output = new byte[height, width];
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                output[i, j] = input[i * width + j];
            }
        }
        return output;
    }

    private static Single[,] single2D(byte[] input, int height, int width)
    {
        Single[,] output = new Single[height, width];
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                output[i, j] = (Single)input[i * width + j];
            }
        }
        return output;
    }

解决方案

This doesn't help with making the code inside the methods cleaner, but I noticed that you have 2 basically identical methods that differ only in their types. I suggest using generics.

This would let you define your method only once. Using the where keyword, you can even limit the kind of types you allow your method to work on.

private static T[,] Make2DArray<T>(T[] input, int height, int width)
{
    T[,] output = new T[height, width];
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            output[i, j] = input[i * width + j];
        }
    }
    return output;
}

You would call this method like this

int[] a;  //or any other array.
var twoDArray = Make2DArray(a, height, width);

这篇关于C#转换一维数组为2D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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