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

How to Remove an Element from a C# Array?

DDD
Release: 2025-01-25 02:02:08
Original
775 people have browsed it

How to Remove an Element from a C# Array?

Remove specific elements from ordinary arrays

When using an array in C#, you may need to remove specific elements from the collection. For ordinary array, unlike the list class, there is no removeat () method that can be used directly. This allows developers to find alternative methods to achieve this function.

Solution:

In order to overcome this limit, you can first convert the ordinary array to List, perform the removal operation, and then convert the modified List to the array, so as to use the List's remaint () method.

Extension method replacement scheme:
<code class="language-c#">var foos = new List<foo>(array);
foos.RemoveAt(index);
return foos.ToArray();</code>
Copy after login

or, you can consider using an expansion method of using an analog ordinary array Removeat () function:

This extension method allows more conveniently to remove operations:

<code class="language-c#">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>
Copy after login

The above is the detailed content of How to Remove an Element from a C# Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template