温馨提示×

C#如何删除数组中指定的值

c#
小亿
119
2024-01-13 15:22:27
栏目: 编程语言

在C#中,可以使用List<T>来代替数组,并使用RemoveAll方法删除指定的值。以下是一个示例:

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);
        }
    }
}

上述示例中,我们首先将数组numbers转换为List<int>对象numberList,然后使用RemoveAll方法删除所有等于3的元素。最后打印结果,只剩下1、2、4、5。

0