Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用linq或sql获取仅在选定批中的学生?_C#_Sql_Linq_Join - Fatal编程技术网

C# 如何使用linq或sql获取仅在选定批中的学生?

C# 如何使用linq或sql获取仅在选定批中的学生?,c#,sql,linq,join,C#,Sql,Linq,Join,我的数据库中有Students、Batches和StudentBatches表。StudentBatches表中将包含StudentBatches和相应的批次,如下所示 学生 ID Name 1 Student'A' 2 Student'B' 3 Student'C' 4 Student'D' 5 Student'E' 批次 ID Name 1 Batch'A' 2 Batch'B' 3 Batch'C' 学生批次 ID StudentID Batch

我的数据库中有Students、Batches和StudentBatches表。StudentBatches表中将包含StudentBatches和相应的批次,如下所示

学生

ID   Name
1   Student'A'
2   Student'B'
3   Student'C'
4   Student'D'
5   Student'E'
批次

ID   Name
1   Batch'A'
2   Batch'B'
3   Batch'C'
学生批次

ID StudentID BatchID
1      1        1
2      2        2
3      2        3
4      3        3
5      4        3
6      5        2
我的要求是,当我给出任何批次ID时,我应该得到仅在该批次中的学生。例如,如果我给出批次ID 3,那么我应该得到3,4个学生ID,因为他们不在任何其他批次中,我不应该得到2个学生ID,因为该学生也在第2批次中。我希望您理解我的要求

我已经用linq编写了这个查询

from batch_student in context.Student_batches
                    group batch_student by batch_student.SID into new_batch_student
                    join student in context.Students on new_batch_student.Key equals student.Id
                    where new_batch_student.Count() == 1 && new_batch_student.Any(x => x.BID == 3)
                    select student;

查询正在工作。但这会对性能产生任何影响吗?是否有任何查询可以获得所需的结果?

另一个选项是取消分组并添加子查询

  var query = from batch in context.Student_batches
              join student in context.Students on batch.SID equals student.Id
              where batch.BID == 3 && 
                    !context.Student_batches.Any(x => x.SID == student.Id && x.BID != batch.BID)
              select student;

请参见这里有一个简单的方法:

var batchID = 3;

var goodStudentIDs = context.Student_batches
    .Where(i => i.BatchID == batchID)
    .Select(i => i.StudentID);

var badStudentIDs = context.Student_batches
    .Where(i => i.BatchID != batchID)
    .Select(i => i.StudentID);

var studentIDs = goodStudentIDs.Except(badStudentIDs);

var students = context.Students.Where(i => studentIDs.Contains(i.ID));
如果您愿意,您可以将这四种陈述合并为一种陈述:

var batchID = 3;

var students = context.Students
    .Where(i => context.Student_batches
    .Where(j => j.BatchID == batchID)
    .Select(j => j.StudentID)
    .Except(context.Student_batches
    .Where(j => j.BatchID != batchID)
    .Select(j => j.StudentID))
    .Contains(i.ID));

你到底有什么问题?您想对性能提出建议,还是您的查询不起作用?