I’m trying to learn Linq and I need help with a method that searches a List within a List, finds a match, and deletes it. For example, imagine I have a class called Student:
public class Student
{
string FirstName;
string LastName;
}
Then imagine I have another class called Classroom, which has a List<Student>:
public class Classroom
{
List<Student> Students;
}
And finally, I have one more class, called School, which has a list of Classrooms:
public class School
{
List<Classroom> Classrooms;
}
Then, I need a method that takes in a Student object, checks to see if the student is in the school, and deletes them if they are. If they’re in the school, the method should delete them and return true. If they’re not in the school, the method should return false and take no action. Here’s an example using foreach loops, which I want to get rid of:
public bool RemoveStudentFromSchool(Student student)
{
foreach (Classroom c in Classrooms)
{
foreach (Student s in c.Students)
{
if ((student.FirstName == s.FirstName) && (student.LastName == s.LastName))
{
s.Remove(student);
return true;
}
}
}
return false;
}
This assumes a student can only be in one room and
StudentisIEquatableon first and last name (or the references are equal):An alternative approach if
Studentis notIEquatableand the search object passed in is not necessarily the same reference: