阅读 167

List <T> .Remove()方法以及C#中的示例

C#List <T>.Remove()方法

C#List <T>.Remove()方法用于从列表中删除给定的项目。

语法:

    bool List<T>.Remove(T item);

参数:接受要从列表中删除的T类型的项目。

返回值:如果成功删除项目,则返回布尔值-如果列表中未找到项目,则返回true-返回false。

示例

    int list declaration:
    List<int> a = new List<int>();

    adding elements:
    a.Add(10);
    a.Add(20);
    a.Add(30);
    a.Add(40);
    a.Add(50);
    
    removing elements
    a.Remove(10)    //将返回true     a.Remove(40)    //将返回true     a.Remove(60)    //将返回假    
    Output:
    20 30 50

C#使用List <T>.Remove()方法从列表中删除项目的示例

using System;using System.Text;using System.Collections.Generic;namespace Test{
    class Program    {
        static void printList(List<int> lst)        {
            //打印元素            foreach (int item in lst)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)        {
            //整数列表            List<int> a = new List<int>();

            //添加元素            a.Add(10);
            a.Add(20);
            a.Add(30);
            a.Add(40);
            a.Add(50);

            //打印列表            Console.WriteLine("list elements...");
            printList(a);

            //删除元素            if (a.Remove(10))
                Console.WriteLine("10 is removed.");
            else                Console.WriteLine("10 does not exist in the list.");

            if (a.Remove(40))
                Console.WriteLine("20 is removed.");
            else                Console.WriteLine("20 does not exist in the list.");

            if (a.Remove(100))
                Console.WriteLine("100 is removed.");
            else                Console.WriteLine("100 does not exist in the list.");

            //删除元素后列出            Console.WriteLine("list elements after removing elements...");
            printList(a);

            //按ENTER退出            Console.ReadLine();
        }
    }
}

输出结果

list elements...10 20 30 40 5010 is removed.20 is removed.100 does not exist in the list.list elements after removing elements...20 30 50


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐