C#将1D数组转换为2D

时间:2015-01-23 15:19:51

标签: c# linq

我发现自己通过执行以下操作将1D字节和单个数组转换为2D。我怀疑它可能和其他方法一样快,但也许有一个更简洁的范例? (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;
    }

4 个答案:

答案 0 :(得分:6)

这对于使方法中的代码更清晰没有帮助,但我注意到你有两个基本相同的方法,它们的类型不同。我建议使用generics

这样您只需定义一次方法。使用where关键字,您甚至可以限制允许方法处理的类型类型。

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

您可以像这样调用此方法

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

答案 1 :(得分:1)

通用功能:

private static b[,] to2D<a, b>(a source, valueAt: Func<a, int, b>, int height, int width)
{
    var result = new b[height, width];
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            result[i, j] = valueAt(source, i * width + j);
        }
    }
    return result;
}

var bytes = to2D<byte[], byte>([], (bytes, at) => bytes[at], 10, 20);

答案 2 :(得分:1)

<script> jQuery(function($) { alert('test'); var validator = $('#searchForm').validate({ rules: { info_test: { required: true } }, messages: {}, errorPlacement: function(error, element) { var placement = $(element).data('error'); if (placement) { $(placement).append(error) } else { error.insertAfter(element); } } }); }); $(document).on('change','input',function(){ $(this).valid(); }); </script> 速度更快,但最快的是根本不复制数组。

如果你真的不需要一个单独的2D数组,你可以通过函数,属性或自定义类型访问像2D阵列这样的一维数组。例如:

Buffer.BlockCopy(input, 0, output, 0, input.Length);

此外,在.NET中,对多维数组的访问比访问锯齿状数组要慢一些

答案 3 :(得分:1)

我知道我参加晚会很晚,但是如果您要访问一个1维数组,列表等,就像它是一个n维数组(不复制),则可以使用https://github.com/henon/SliceAndDice来做到这一点,复制。

// create a 2D array of bytes from a byte[]
var a = new ArraySlice<byte>( new byte[100], new Shape(10,10));
// now access with 2d coordinates
a[7,9]=(byte)56;

当然,每个人都可以轻松地完成简单的2d,3d等。但是,该库还允许对n维数组进行切片,而无需复制。