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.
A subset of an array is similar to a subset of a set. We print all the possible combinations of the array using each element, (including phi) which means no elements of the array.
Array-slicing is supported in the print and display commands for C, C++, and Fortran. Expression that should evaluate to an array or pointer type.
Steps. Set snum = 0. If the ith digit of snum in binary is 1 then it means ith index of input array is included in the subset. If ith digit of snum in binary is 0, then ith index of input array is not included in the subset.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With