Linq lambda,用于在列表中搜索列表,找到匹配项,然后将其从列表中删除

本文关键字:列表 然后 删除 用于 lambda 搜索 Linq | 更新日期: 2023-09-27 17:59:12

我正在尝试学习Linq,我需要一个方法来帮助我在列表中搜索列表,找到匹配项并删除它。例如,假设我有一个名为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;
}

Linq lambda,用于在列表中搜索列表,找到匹配项,然后将其从列表中删除

这假设一个学生只能在一个房间里,并且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;

扩展方法怎么样。。

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