Subset of Array in C#

后端 未结 8 1242
别跟我提以往
别跟我提以往 2020-12-05 16:49

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:

__ __ __ _         


        
8条回答
  •  粉色の甜心
    2020-12-05 17:46

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

提交回复
热议问题