Alex Rivera | Logout

How to delete an item from a generic list

Asked 2011-02-04T23:22:50.223
15

I have a generic list

How do I remove an item?

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...???
    }
}
Edit
Report

2 Answers

25

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
}
answered 2011-02-04T23:24:09.143
3
List<Student> students = new List<Student>();
students.Add(new Student {StudentId = 1, StudentName = "Bob",});
students.RemoveAt(0); //Removes the 1st element, will crash if there are no entries

OR to remove a known Student.

//Find a Single Student in the List.
Student s = students.Where(s => s.StudentId == myStudentId).Single();
//Remove that student from the list.
students.Remove(s);
answered 2011-02-04T23:25:52.280

Your Answer