Remove element of a regular array

前端 未结 15 2487
野性不改
野性不改 2020-11-22 10:06

I have an array of Foo objects. How do I remove the second element of the array?

I need something similar to RemoveAt() but for a regular array.

15条回答
  •  一生所求
    2020-11-22 10:29

    This is a way to delete an array element, as of .Net 3.5, without copying to another array - using the same array instance with Array.Resize:

    public static void RemoveAt(ref T[] arr, int index)
    {
        for (int a = index; a < arr.Length - 1; a++)
        {
            // moving elements downwards, to fill the gap at [index]
            arr[a] = arr[a + 1];
        }
        // finally, let's decrement Array's size by one
        Array.Resize(ref arr, arr.Length - 1);
    }
    

提交回复
热议问题