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:
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);