我想了解如何使用“包含”而不是“等于”來加入兩個串列。SO上有類似的問題,但似乎沒有任何效果。這是我的示例代碼,我的目的是讓不屬于任何教室的學生:
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;
如您所見,我可以使用 optionA 得到答案,但我想了解是否可以使用 optionB 中的方法完成它?
uj5u.com熱心網友回復:
嘗試以下查詢:
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;
uj5u.com熱心網友回復:
當您的目標是找到不屬于的人(與加入相反)時,我認為我不會說您正在“加入”兩個串列。
因此,我將創建 aHashSet中的所有Students,ClassRoom然后找到Student不在該集合中的 s:
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;
我認為加入 byContains更像是生成一個Students 串列和ClassRoom它們所屬的 s (假設 aStudent可能在多個中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 };
uj5u.com熱心網友回復:
var studentsWithoutClassRoomTest = from w in students
from l in classes
where !l.Students.Contains(w)
select l;
如果你想要學生,你不應該選擇w而不是選擇嗎?l
使用join代替from并給出加入條件on
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/515627.html
標籤:C#林克
下一篇:AsNoTracking拋出錯誤方法'System.Data.Entity.Infrastructure.DbQuery在型別為DbSet上宣告,其中包含集合
