How do I clone a range of array elements to a new array?

Have you considered using ArraySegment?

http://msdn.microsoft.com/en-us/library/1hsbd92d.aspx


You can use Array.Copy(...) to copy into the new array after you've created it, but I don't think there's a method which creates the new array and copies a range of elements.

If you're using .NET 3.5 you could use LINQ:

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

but that will be somewhat less efficient.

See this answer to a similar question for options for more specific situations.


You could add 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 re cloning (which wasn't obvious in the original question). If you really want a deep clone; 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);
    }
}

This does require the objects to be serializable ([Serializable] or ISerializable), though. You could easily substitute for any other serializer as appropriate - XmlSerializer, DataContractSerializer, protobuf-net, etc.

Note that deep clone is tricky without serialization; in particular, ICloneable is hard to trust in most cases.


I see you want to do Cloning, not just copying references. In this case you can use .Select to project array members to their clones. For example, if your elements implemented IClonable you could do something like this:

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

Note: This solution requires .NET Framework 3.5.