简体   繁体   中英

How to Convert int[] to int[,] - C#

I have an int array in one dimension:

var intArray=new[] { 1, 2, 3, 4, 5, 6 };

and I want to convert it to two dimensions, such as:

var intArray2D=new[,] { {1, 2}, {3, 4}, {5, 6} };

How do I achieve this with C#?

with a loop perhaps:

for (int i = 0; i < oldArr.Length; i=i+2)
{
    newArr[i/2, 0] = oldArr[i];
    newArr[i/2, 1] = oldArr[i + 1];
}

Untested, but should get you pointed in the right direction...

If the one dimensional array contains the primitive data in row major order , and the total capacity of the 2 dimensional array equals the length of the one dimensional array, you can use this.

int[] source = new int[6];
int[,] target = new int[3, 2];
Buffer.BlockCopy(source, 0, target, 0, source.Length * sizeof(int));

Note that unlike Array.Copy and other array/list methods, Buffer.BlockCopy operates on a number of bytes of data, even if each element of the array is larger than 1 byte. It also only operates on arrays of primitive data types.

Additional references:

Edit: Here is a complete unit test.

[TestMethod]
public void SOTest16203210()
{
    int[] source = new int[6] { 1, 2, 3, 4, 5, 6 };
    int[,] destination = new int[3, 2];
    Buffer.BlockCopy(source, 0, destination, 0, source.Length * sizeof(int));
    Assert.AreEqual(destination[0, 0], 1);
    Assert.AreEqual(destination[0, 1], 2);
    Assert.AreEqual(destination[1, 0], 3);
    Assert.AreEqual(destination[1, 1], 4);
    Assert.AreEqual(destination[2, 0], 5);
    Assert.AreEqual(destination[2, 1], 6);
}

I believe you want to split an integer array into an array of two integers each:

int[] list = new int[] { 1, 2, 3, 4, 5, 6};
int[][] newlist = new int[list.Length / 2][];
for (int i = 0, n = 0; i < list.Length; i += 2, n++)
{
    newlist[n] = new[] { list[i], list[i + 1] };
}

To assign it to Points in particular you could try:

List<Point> plist = new List<Point>();
for (int i = 0; i < list.Length; i += 2)
{
    plist.Add(new Point(list[i], list[i + 1]));
}

you may use this code. in here you can send any length you like. you can "deivde" the arry[] to arry[,] for any lenth.2 or 3 or what ever you like! as long as size % a.length ==0 !!!!

code

        static int[,] convert(int[] a, int size)
    {
        int[,] value = new int[a.Length / size, size];
        int counter = 0;
        //
        for (int b = 0; b < value.GetLength(0); b++)
            for (int c = 0; c < value.GetLength(1); c++)
            {
                 value[b, c] = a[counter];
                  counter++;
           }
        return value;
    }

If the product of the dimensions are the same, the fastest way would probably be to pin the matrix using a fixed statement, then to use the Marshalling class to copy the continuous block from the array to an IntPtr created from the void* you got from the fixed.

You would have to wrap this in an unsafe statement and enable unsafe in the assembly's build config.

You could try this:

int [] a = {1,2,3,4,5,6};
int [,] b = new int[a.Length/2,2];

for(int i = 0;i<a.Length;i++)
{
    b[i/2,i%2] = a[i];
}

Note that i/2 is an integer division, hence both 4/2 and 5/2 will give 2 which is a correct index in 2Darray for the tuple 5 and 6 from the original array. The second index is determined using reminder when divided by 2, it will give 0 if the index is even number and 1 if the index of the item from the original array is odd number.

I have converted this from vb to c#

int Size = OldArray.Length;
int[,] NewPoints = null;

if (Size % 2 != 0) {
  //Error - Array has odd number of elements!
} else {
  for (i = 0; i <= Size - 1; i += 2) {
    Array.Resize(ref AllPoints, (i / 2) + 1, 2);
    NewPoints[i / 2, 0] = OldArray(i);
    NewPoints[i / 2, 1] = OldArray(i + 1);
  }
}

I would consider this for any dimension of array:

public class TestClass {
    public static void TestMethod2D() {
        var intLinear=new[] { 1, 2, 3, 4, 5, 6 };
        var indexer2D=new ArrayIndexer<int>(3, 2);

        for(var i=intLinear.Length; i-->0; indexer2D[i]=intLinear[i])
            ;

        var int2D=(int[,])indexer2D.ToArray();
    }

    public static void TestMethod4D() {
        var intLinear=new[] { 1, 2, 3, 4, 5, 6 };
        var indexer4D=new ArrayIndexer<int>(2, 2, 2, 2);

        for(var i=intLinear.Length; i-->0; indexer4D[i]=intLinear[i])
            ;

        var int4D=(int[, , ,])indexer4D.ToArray();
    }
}

public partial class ArrayIndexer<T> {
    public Array ToArray() {
        return m_Array;
    }

    public ArrayIndexer(params int[] lengths) {
        m_Array=Array.CreateInstance(typeof(T), lengths);
    }

    public T this[params int[] indices] {
        set {
            m_Array.SetValue(value, indices.Transform(m_Array));
        }

        get {
            return (T)m_Array.GetValue(indices.Transform(m_Array));
        }
    }

    Array m_Array;
}

public static partial class ArrayExtensions {
    public static int[] Transform(
        this int[] indices, Array array, bool isRowMajor=true) {
        if(indices.Length>array.Rank)
            return indices;
        else {
            var list=indices.ToList();

            if(isRowMajor)
                list.Reverse();

            for(int r, q=0, i=0, count=array.Rank; count-->0; ++i) {
                var index=isRowMajor?count-i:i;

                if(indices.Length>i) {
                    q=Math.DivRem(indices[i]+q, array.GetLength(index), out r);
                    list[i]=r;
                }
                else {
                    if(index<0) {
                        list.Add(q);
                        q=0;
                    }
                    else {
                        q=Math.DivRem(q, array.GetLength(index), out r);
                        list.Add(r);
                    }
                }
            }

            if(isRowMajor)
                list.Reverse();

            return list.ToArray();
        }
    }
}

ArrayExtensions.Transform is an indices transformer, it performs the linear transformation with the geometry of a given array. isRowMajor controls the layout, such as you would regard an int[,] in x, y or in y, x order.

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