Home > Backend Development > C++ > How to Efficiently Delete Elements from a C# Array by Value?

How to Efficiently Delete Elements from a C# Array by Value?

Mary-Kate Olsen
Release: 2025-01-20 20:50:14
Original
120 people have browsed it

How to Efficiently Delete Elements from a C# Array by Value?

Remove elements from array in C#

Scene:

Suppose you have an array of integers:

<code class="language-c#">int[] numbers = {1, 3, 4, 9, 2};</code>
Copy after login

You want to remove elements with a specific value (for example, 4). Although you can use ArrayList to manage arrays, its RemoveAt method does not allow filtering based on element values.

Solution:

To remove elements from an array by name (value), you can use LINQ or non-LINQ methods.

LINQ method (.NET Framework 3.5):

Using LINQ’s Where method, you can filter elements and exclude those you want to delete:

<code class="language-c#">int[] numbers = { 1, 3, 4, 9, 2 };
int numToRemove = 4;
numbers = numbers.Where(val => val != numToRemove).ToArray();</code>
Copy after login

Non-LINQ method (.NET Framework 2.0):

For environments without LINQ, you can use the built-in Array method to achieve the same result:

<code class="language-c#">static bool isNotFour(int n)
{
    return n != 4;
}

int[] numbers = { 1, 3, 4, 9, 2 };
numbers = Array.FindAll(numbers, isNotFour);</code>
Copy after login

Delete only the first instance:

If you only want to remove the first occurrence of a specific element:

LINQ method:

<code class="language-c#">int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();</code>
Copy after login

Non-LINQ methods:

<code class="language-c#">int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIdx = Array.IndexOf(numbers, numToRemove);
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(numIdx);
numbers = tmp.ToArray();</code>
Copy after login

The above is the detailed content of How to Efficiently Delete Elements from a C# Array by Value?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template