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>
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>
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>
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>
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>
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!