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.
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" }
.