Home > Back-end >  two arrays to one 2D
two arrays to one 2D

Time:04-29

I have two arrays that are same length and type and I would like to combine them into one with same length and 2 rows.

for example:

      VolunteeringForWardLogicData[] v1, v2;

and I want each of the arrays will be in a row in this matrix:

     VolunteeringForWardLogicData[,] arr= new VolunteeringForWardLogicData[2, v1.Length];

how can i do it? i saw this example Combining same length arrays into one 2d array in f#

but I did not really understand how it works.

Thanks in advance.

CodePudding user response:

You can just use a loop to assign the items from the source lists to your new list:

void Main()
{
    var list1 = new int[] { 1, 2, 3, 4 };
    var list2 = new int[] { 11, 12, 13, 14 };
    
    var combined = new int[2, list1.Length];
    for (var i = 0; i < list1.Length; i  )
    {
        combined[0, i] = list1[i];
        combined[1, i] = list2[i];
    }
    
    for (var i = 0; i < list1.Length; i  )
    {
        Console.WriteLine($"{combined[0, i]}: {combined[1, i]}");
    }
}

Or, you could create an array of arrays (slightly different to your request) by using Enumerable's Zip function:

void Main()
{
    var list1 = new int[] { 1, 2, 3, 4 };
    var list2 = new int[] { 11, 12, 13, 14 };
    
    var combined = list1.Zip(list2, (a, b) => new int[]{a, b});
    
    foreach (var item in combined) 
    {
        Console.WriteLine($"{item[0]}: {item[1]}");
    }
}

Output:

1: 11
2: 12
3: 13
4: 14

CodePudding user response:

You can use Spans, it will be much faster than for loops:

static T[,] CombineArrays<T>(T[] array1, T[] array2)
{
    if (array1.Length != array2.Length)
        throw new ArgumentException("arrays must have the same length");

    var ret = new T[2, array1.Length];

    Span<T>
        row1 = MemoryMarshal.CreateSpan(ref ret[0, 0], array1.Length),
        row2 = MemoryMarshal.CreateSpan(ref ret[1, 0], array2.Length);

    array1.CopyTo(row1);
    array2.CopyTo(row2);

    return ret;
}
  • Related