Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot remove an Item from a C# list

I have a C# list of students. I cannot remove Item based on Id.

Program.cs

static void RemoveStudent(StudentManager studentManager)
{
    Console.WriteLine("Which student? Insert ID:");
    int id = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine(id);
    studentManager.RemoveStudent(1);
}

How student class looks like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Major { get; set; }
}

How StudentManagerClass looks like:

public class StudentManager
{
    private List<Student> students = new List<Student>();

    public void RemoveStudent(int id)
    {
        students.RemoveAt(id);
    }
   
    //...
}

Program exits without any prompt when trying to remove the element.

>Solution :

List.RemoveAt is documented to do the following:

Removes the element at the specified index of the List.

(emphasys in mine)

In your case id is not the index of the element, but rather the value of a specific field of it.

In order to remove an element by a given field, you can use List.RemoveAll which:

Removes all the elements that match the conditions defined by the specified predicate.

In this predicate you can compare the Id field to the one you want to remove:

//----------------------------vvvvvvvvvvvvvvvv--
students.RemoveAll(student => student.Id == id);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading