我正在尝试学习Linq,我需要一个方法来帮助查找List中的List,查找匹配项并删除它。例如,假设我有一个名为Student
的类:
public class Student
{
string FirstName;
string LastName;
}
然后想象我有另一个名为Classroom
的班级,其中有List<Student>
:
public class Classroom
{
List<Student> Students;
}
最后,我还有一个名为School
的课程,其中有一个Classrooms
列表:
public class School
{
List<Classroom> Classrooms;
}
然后,我需要一个接收Student
对象的方法,检查学生是否在学校,如果是,则删除它们。如果他们在学校,该方法应删除它们并返回true。如果他们不在学校,该方法应该返回false并且不采取任何行动。这是一个使用foreach循环的例子,我想摆脱它:
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;
}
答案 0 :(得分:3)
这假设学生只能在一个房间,Student
IEquatable
姓名(或参考文献相同):
var roomWithStudent = Classrooms.FirstOrDefault(c => c.Students.Any(s => s.Equals(student));
if (roomWithStudent != null)
{
roomWithStudent.Remove(student);
return true;
}
return false;
如果Student
不是IEquatable
并且传入的搜索对象不一定是同一个引用,那么另一种方法是:
var roomWithStudent = Classrooms
.SelectMany(c => c.Students.Select(s => new { Room = c, Student = s }))
.Where(rs => (student.FirstName == rs.Student.FirstName) && (student.LastName == rs.Student.LastName))
.FirstOrDefault();
if (roomWithStudent != null)
{
roomWithStudent.Room.Students.Remove(roomWithStudent.Student);
return true;
}
return false;
答案 1 :(得分:1)
扩展方法怎么样..
public static bool RemoveFromRoom(this Student student,School school)
{
if (student == null) throw new ArgumentNullException("student");
if (school == null) throw new ArgumentNullException("school");
bool ret = false;
var room = school.Classrooms.SingleOrDefault(cr=>cr.Students.Contains(student));
if (room !=null)
{
ret = true;
room.Students.Remove(student);
}
return ret;
}
用法
student.RemoveFromRoom(instanceOfSchool);
或者...
public static bool RemoveStudentFromRoom(this School school,Student student)
{
if (student == null) throw new ArgumentNullException("student");
if (school == null) throw new ArgumentNullException("school");
bool ret = false;
var room = school.Classrooms.SingleOrDefault(cr=>cr.Students.Contains(student));
if (room !=null)
{
ret = true;
room.Students.Remove(student);
}
return ret;
}
用法
instanceOfSchool.RemoveStudentFromRoom(student);