0

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.

N.A
  • 68
  • 8

2 Answers2

1

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
JohnLBevan
  • 22,735
  • 13
  • 96
  • 178
1

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;
}
Petrusion
  • 940
  • 4
  • 11
  • Thank you, Do I need to add anything to use MemoryMarshal and Span? – N.A Apr 28 '22 at 12:14
  • @N.A You won't have them only if you are using an old version of C# / .Net. They've been in the standard library for a few years. `MemoryMarshal` is in `System.Runtime.InteropServices` namespace. – Petrusion Apr 28 '22 at 12:18
  • in order to use Span i added the Nuget Package System.Memory,But in what command to change the command MemoryMarshal.CreateSpan? – N.A Apr 28 '22 at 12:42
  • @N.A You are probably using some old .Net version if you needed to add a Nuget package. If you don't have `Span`s and `MemoryMarshal` available out of the box, stick to `for` loops for or `Zip` 2d arrays – Petrusion Apr 28 '22 at 13:50