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

c#
982
2023/12/24 15:22:27
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c#中break和continue的区别是什么