Efficiently remove elements from C# array
In C#, there are various ways to remove elements from an array, especially when you need to remove elements by "name". Here are some effective techniques:
Remove specific instances using LINQ
If you need to remove all specific elements (e.g. "4") without needing their index, you can leverage LINQ:
<code class="language-csharp">int[] numbers = { 1, 3, 4, 9, 2 }; int numToRemove = 4; numbers = numbers.Where(val => val != numToRemove).ToArray();</code>
Non-LINQ method removes first instance
To remove only the first instance of an element, a non-LINQ method is more suitable:
<code class="language-csharp">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>
Other notes
Please note that the LINQ examples require .NET Framework 3.5 or higher. For .NET Framework 2.0, you need to use the provided non-LINQ examples.
The above is the detailed content of How Can I Efficiently Remove Elements from a C# Array by Name?. For more information, please follow other related articles on the PHP Chinese website!