sscotti
asked on
Copy arbitrary sized array, multiple dimensions and length in C#
Is there a way to create a method, or is there an existing method for Array objects, to copy an arbitrary sized array into a new array. This isn't that difficult if you know what size and dimensions the original array has, but I am a beginner with c# and I don't know how to copy an array of arbitrary dimensions and size into a new array of the same dimension and length. I would rather create a method from scratch rather than using some of the built-in methods for Arrays. It is easy enough to copy into a one-dimsionsal array.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CopyMe
{
class Program
{
static void Main(string[] args)
{
int[,] input = new int[3,2];
input[0, 0] = 1;
input[0, 1] = 2;
input[1, 0] = 3;
input[1, 1] = 4;
input[2, 0] = 5;
input[2, 1] = 6;
int[] newArray = CopyMe(input);
int index = 0;
foreach (int value in newArray)
{
Console.WriteLine("Value at index {0} is {1}", index, value);
index++;
}
Console.ReadLine();
}
public static int[] CopyMe(Array input)
{
int[] newArray = new int[input.Length];
int position = 0;
foreach (int index in input)
{
// Console.Write(index);
newArray[position] = index;
position++;
}
Console.WriteLine("Incoming array rank is {0}", input.Rank);
Console.WriteLine("Incoming array length is {0}", input.Length);
Console.WriteLine(input.GetLength(0));
Console.WriteLine("Hit return to print new array values.");
Console.ReadLine();
return newArray;
}
}
}
Use Array.Copy (example at the bottom).
ASKER
I don't think that that covers the cases where the original array is arbitrary rank. i.e. [3,2,4,5], [3,3,4,6,7], [4,6,7,8,9,10,11], etc.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.