Remove element of a regular array

前端 未结 15 2485
野性不改
野性不改 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:39

    LINQ one-line solution:

    myArray = myArray.Where((source, index) => index != 1).ToArray();
    

    The 1 in that example is the index of the element to remove -- in this example, per the original question, the 2nd element (with 1 being the second element in C# zero-based array indexing).

    A more complete example:

    string[] myArray = { "a", "b", "c", "d", "e" };
    int indexToRemove = 1;
    myArray = myArray.Where((source, index) => index != indexToRemove).ToArray();
    

    After running that snippet, the value of myArray will be { "a", "c", "d", "e" }.

提交回复
热议问题