如何从通用列表中删除项目 [英] How to delete an item from a generic list

查看:114
本文介绍了如何从通用列表中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用列表

如何删除某个项目?

EX:

Class Student
{
    private number;
    public Number
    {
        get( return number;)
        set( number = value;)
    }

    private name;
    public Name
    {
        get( return name;)
        set( name = value;)
    }

    main()
    {
        static List<student> = new list<student>();

        list.remove...???
    }
}


推荐答案

,没有什么可以删除的,因为你的列表是空的(你也没有给它一个标识符,所以你的代码不会编译)。您可以使用 Remove(T item) RemoveAt(int index)来移除一个对象或一个对象指定的索引(一旦它实际上包含某些内容)。

Well, there is nothing to remove because your list is empty (you also didn't give it an identifier, so your code won't compile). You can use the Remove(T item) or RemoveAt(int index) to remove an object or the object at a specified index respectively (once it actually contains something).

创建的代码示例:

Contrived code sample:

void Main(...)
{
    var list = new List<Student>();
    Student s = new Student(...);
    list.Add(s);

    list.Remove(s); //removes 's' if it is in the list based on the result of the .Equals method

    list.RemoveAt(0); //removes the item at index 0, use the first example if possible/appropriate
}

这篇关于如何从通用列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆