Coder Perfect

How can I copy a set of array elements into a new one?


I have a ten-element array X. I’d want to make a new array with all of the elements from X starting at index 3 and ending at index 7. Sure, I could construct a loop to do it for me, but I’d prefer to keep my code as simple as possible. Is there a C# technique that can help me with this?

Something along the lines of (pseudo code):

Array NewArray = oldArray.createNewArrayFromRange(int BeginIndex , int EndIndex)

Array. Copy does not meet my requirements. I require clones of the elements in the new array. Array.copy is just a C-style memcpy counterpart; it’s not what I’m after.

Asked by user88637

Solution #1

It’s possible to include it as an extension method:

public static T[] SubArray<T>(this T[] data, int index, int length)
    T[] result = new T[length];
    Array.Copy(data, index, result, 0, length);
    return result;
static void Main()
    int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int[] sub = data.SubArray(3, 4); // contains {3,4,5,6}

Update on cloning (which wasn’t clear in the first inquiry). If you’re looking for a deep clone, try something like:

public static T[] SubArrayDeepClone<T>(this T[] data, int index, int length)
    T[] arrCopy = new T[length];
    Array.Copy(data, index, arrCopy, 0, length);
    using (MemoryStream ms = new MemoryStream())
        var bf = new BinaryFormatter();
        bf.Serialize(ms, arrCopy);
        ms.Position = 0;
        return (T[])bf.Deserialize(ms);

The objects must be serializable ([Serializable] or ISerializable) for this to work. Any other serializer, such as XmlSerializer, DataContractSerializer, protobuf-net, and so on, might easily be substituted.

Without serialization, deep cloning is difficult; in particular, ICloneable is difficult to trust in most circumstances.

Answered by Marc Gravell

Solution #2

You can make use of Array. After you’ve formed the new array, you can copy into it using Copy(…), but I don’t believe there’s a technique that constructs the new array and duplicates a range of elements.

If you have.NET 3.5 installed, you can use LINQ:

var newArray = array.Skip(3).Take(5).ToArray();

However, this will be less efficient.

For more particular instances, see this solution to a similar topic.

Answered by Jon Skeet

Solution #3

Have you explored ArraySegment as an option?

Answered by Alex Black

Solution #4

I see you’re interested in cloning rather than just copying references. You can utilise in this scenario. To project array members to their clones, select this option. If your elements used IClonable, for example, you could do something like this:

var newArray = array.Skip(3).Take(5).Select(eachElement => eachElement.Clone()).ToArray();

This method necessitates the use of the.NET Framework 3.

Answered by zvolkov

Solution #5

The following code accomplishes this in a single line:

// Source array
string[] Source = new string[] { "A", "B", "C", "D" };
// Extracting a slice into another array
string[] Slice = new List<string>(Source).GetRange(2, 2).ToArray();

Answered by Volker

Post is based on