Home > Backend Development > C++ > How to Remove an Element from a Regular Array in C#?

How to Remove an Element from a Regular Array in C#?

Mary-Kate Olsen
Release: 2025-01-25 02:22:09
Original
289 people have browsed it

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):
var foos = new List<foo>(array);
foos.RemoveAt(index);
return foos.ToArray();
Copy after login

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:

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;
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template