Subset of Array in C#

后端 未结 8 1249
别跟我提以往
别跟我提以往 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条回答
  •  萌比男神i
    2020-12-05 17:35

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

提交回复
热议问题