Subset of Array in C#

LINQ is your friend. :)

var newArray = oldArray.Skip(1).Take(oldArray.Length - 2).ToArray();

Somewhat less efficient than manually creating the array and iterating over it of course, but far simple...

The slightly lengithier method that uses Array.Copy is the following.

var newArray = new int[oldArray.Count - 2];
Array.Copy(oldArray, 1, newArray, 0, newArray.Length);

Linq is all nice and snazzy, but if you're looking for a 1-liner you could just throw together your own utility functions:

static class ArrayUtilities
{
    // create a subset from a range of indices
    public static T[] RangeSubset<T>(this T[] array, int startIndex, int length)
    {
        T[] subset = new T[length];
        Array.Copy(array, startIndex, subset, 0, length);
        return subset;
    }

    // create a subset from a specific list of indices
    public static T[] Subset<T>(this T[] array, params int[] indices)
    {
        T[] subset = new T[indices.Length];
        for (int i = 0; i < indices.Length; i++)
        {
            subset[i] = array[indices[i]];
        }
        return subset;
    }
}

So then you could do the following:

        char[] original = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };

        // array containing 'b' - 'f'
        char[] rangeSubset = original.RangeSubset(1, original.Length - 2);

        // array containing 'c', 'd', and 'f'
        char[] specificSubset = original.Subset(2, 3, 5);

You can use ArraySegment<T> structure like below:

var arr = new[] { 1, 2, 3, 4, 5 };
var offset = 1;
var count = 2;
var subset = new ArraySegment<int>(arr, offset, count)
             .ToArray(); // output: { 2, 3 }

Check here for an extension method that makes use of it even easier.

Tags:

C#

Arrays