使用linq查询语法连接两个列表的最快方法是什么?

hwamh0ep  于 2022-12-06  发布在  其他
关注(0)|答案(3)|浏览(913)

我想知道如何使用“contains”而不是“equals”来连接两个列表。在SO上也有类似的问题,但似乎都不起作用。下面是我的示例代码,我的目标是让不属于任何classRoom的学生:

var a = new Student("A");
        var b = new Student("B");
        var c = new Student("C");
        var d = new Student("D");
        var e = new Student("E");
        var f = new Student("F");
        var students = new List<Student>() { a, b, c, d, e, f };

        var classRoomA = new ClassRoom();
        classRoomA.Students.Add(a);
        classRoomA.Students.Add(b);

        var classRoomB = new ClassRoom();
        classRoomB.Students.Add(c);
        classRoomB.Students.Add(d);

        var classRoomC = new ClassRoom();
        classRoomC.Students.Add(e);

        var classes = new List<ClassRoom> { classRoomA, classRoomB, classRoomC };

        //option A. This works
        var studentsWithoutClassRoom = students
            .Where(stu => !classes.Any(r => r.Students.Contains(stu)))
            .Select(s => s);

        //optionB .This in one of many options that
        //I have tried and it gives very interesting results
        var studentsWithoutClassRoomTest = from w in students
                                           from l in classes
                                           where !l.Students.Contains(w)
                                           select l;

正如您所看到的,我可以使用选项A得到答案,但我想了解的是,是否可以使用选项B中的方法来完成它?

fkaflof6

fkaflof61#

请尝试下列查询:

var studentsWithoutClassRoomTest = 
    from w in students
    join s in classes.SelectMany(c => c.Students) on w equals s into gj
    from s in gj.DefaultIfEmpty()
    where s == null
    select w;
jhdbpxl9

jhdbpxl92#

我不认为我会说你是"加入"两个名单时,你的目标是找到那些谁不属于(更多的相反加入)。
所以我会创建一个ClassRoom中所有StudentHashSet,然后找到不在那个集合中的Student

var studentsWithClassRooms = (from cr in classRooms
                             from s in cr.Students
                             select s).ToHashSet();
var studentsWithoutClassRoomTest = from s in students
                                   where !studentsWithClassRooms.Contains(s)
                                   select s;

我认为通过Contains加入更像是产生一个Student和它们所属的ClassRoom的列表(假设一个Student可以在多个ClassRoom中):

var studentsAndClassRooms = from s in students
                            from cr in classRooms
                            where cr.Students.Contains(s)
                            group cr by s into crg
                            select new { s = crg.Key, crg };
qgzx9mmu

qgzx9mmu3#

var studentsWithoutClassRoomTest = from w in students
    from l in classes
    where !l.Students.Contains(w)
    select l;

如果你想要学生,你不应该选择w而不是l吗?
使用join代替from,并使用on给出联接条件

相关问题