Home >Backend Development >C++ >How to Remove an Element from a Regular Array in C#?
Remove the element from the ordinary array
Q: I need to remove an element from an ordinary object array. Specifically, I want to remove the second element. Is there a way to do the REMOVEAT () method similar to the list?
Answer 1 (use list):
If you are willing to use a list, you can convert the array to a list, remove the element, and then convert it back to the array.
Answer 2 (extension method):
<code class="language-csharp">var foos = new List<foo>(array); foos.RemoveAt(index); return foos.ToArray();</code>
As an alternative to using a list, you can use an extension method specialized for this task. This is an example:
With this expansion method, you can remove the second element like this:
<code class="language-csharp">public static T[] RemoveAt<T>(this T[] source, int index) { T[] dest = new T[source.Length - 1]; if (index > 0) Array.Copy(source, 0, dest, 0, index); if (index < source.Length - 1) Array.Copy(source, index + 1, dest, index, source.Length - index - 1); return dest; }</code>
The above is the detailed content of How to Remove an Element from a Regular Array in C#?. For more information, please follow other related articles on the PHP Chinese website!