Subset of Array in C#

If I have an array with 12 elements and I want a new array with that drops the first and 12th elements. For example, if my array looks like this:

__ __ __ __ __ __ __ __ __ __ __ __
a  b  c  d  e  f  g  h  i  j  k  l
__ __ __ __ __ __ __ __ __ __ __ __

I want to either transform it or create a new array that looks like

__ __ __ __ __ __ __ __ __ __

b  c  d  e  f  g  h  i  j  k 
__ __ __ __ __ __ __ __ __ __

I know I can do it by iterating over them. I was just wondering if there was a cleaner way built into C#.

**UPDATED TO FIX A TYPO. Changed 10 elements to 12 elements.

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);

Array subset array-subset.aspx <%@ Page Language="C#" AutoEventWireup="true"%> <!DOCTYPE html> <script runat="server"> pr

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);

Array slice. A slice of an array is a range of elements. By using extension methods and generics, we simplify and clarify array slices. This makes for more reusable and powerful code. We write and test an array slice method.Array

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.

Is there a method in C# that can do it for me? Something like (pseudo code): Array NewArray = oldArray.createNewArrayFromRange(int BeginIndex , int EndIndex) Array.Copy doesn't fit my needs. I need the items in the new array to be clones. Array.copy is just a C-Style memcpy equivalent, it's not what I'm looking for.

You can do this with Array.Copy or LINQ.

var letters = string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i" };

int length = letters.Length - 2;
var items = new string[length];
Array.Copy(letters, 1, items, 0, length);
// or
var items = letters.Skip(1).Take(length).ToArray();

Find whether an array is subset of another array using Map; Find the minimum value to be added so that array becomes balanced; Check if array elements are consecutive | Added Method 3; Find if there is any subset of size K with 0 sum in an array of -1 and +1; k largest(or smallest) elements in an array | added Min Heap method

C# 8 has a Range and Index type

char[] a = { 'a', 'b', 'c',  'd',  'e',  'f',  'g',  'h',  'i',  'j',  'k',  'l' };
Index i1 = 1;  // number 1 from beginning
Index i2 = ^1; // number 1 from end
var slice = a[i1..i2]; // { 'b','c','d','e','f','g','h','i','j' }

Assuming you know the size of your 'main' array and that is an integer array, you can do this: subset = malloc((arraySize-i)*sizeof(int)); //Where i is the place you want to start your subset. for(j=i;j<arraySize;j++) subset[j] = originalArray[j];

Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 64-bit integers. Copies a range of elements from an Array starting at the specified source index

Efficiently merging two sorted arrays with O(1) extra space and O(NlogN + MlogM) Find XOR of all elements in an Array; Split the given string into Primes : Digit DP; Number of pairs in an array with the sum greater than 0; Count of subsets with sum equal to X using Recursion; Check if sum of Fibonacci elements in an Array is a Fibonacci number or not

C# Program for Subset Sum Problem | DP-25 Given a set of non-negative integers, and a value sum , determine if there is a subset of the given set with sum equal to given sum . Example:

Comments
  • Isn't "j" the 10th element in the array though? Or did you mean first and last elements?
  • I really liked your original answer. LINQ has been my friend for sometime. I'd just never used skip and take. Thanks.
  • @L. Moser: No problem - changed back too. :) And yeah, I think I discover a new useful LINQ method every week or so.
  • Wouldn't this be simpler if you did the Skip after the Take? Like: oldArray.Take(oldArray.Length - 1).Skip(1).ToArray()? Either way are likely equal in effeciency.
  • Not a good application of LINQ. If you're already down at the char array level then do it right.
  • @rolls, Fixed, ta!
  • This doesn't appear to drop the last element.