How to remove a specified value from an array in C#?

In C#, you can use List instead of an array, and use the RemoveAll method to delete specific values. Here is an example:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 定义一个包含指定值的数组
        int[] numbers = { 1, 2, 3, 4, 5, 3 };

        // 转换为List
        List<int> numberList = new List<int>(numbers);

        // 删除指定的值
        numberList.RemoveAll(n => n == 3);

        // 打印结果
        foreach (int number in numberList)
        {
            Console.WriteLine(number);
        }
    }
}

In the example above, we first convert the array numbers into a List object called numberList. Then, we use the RemoveAll method to delete all elements equal to 3. Finally, we print the remaining elements, which are 1, 2, 4, and 5.

bannerAds