LINQ查询特定情况2

时间:2019-01-23 18:23:57

标签: c# .net linq

可以说我有以下表格:

 Student(id(pk), name)
 Class(id(pk), name)
 StudentClass(id(pk), studentId(fk), classId(fk))

想象一下:

Student表包含:

 (1,"John"), (2, "Mike"), (3,"Josh")

Class表包含:

(1,"Geography"), (2, "Math"), (3, "History"), (4,"Biology)"

StudentClass表包含:

(`1, 1, 1),(2,2,2),(3,3,2)

现在让我们假设我有一个StudentClassDTO类,其中包含

List<string> StudentNames
string ClassName

如何使用LINQ查询将数据获取到StudentClassDTO中?任何帮助表示赞赏。

因此最终数据将是

  1. {约翰,地理}
  2. {[Mike,Josh]数学}
  3. {NULL,历史记录}
  4. {Null,生物学}

我尝试了左外部联接,但找不到方法。

3 个答案:

答案 0 :(得分:1)

这是使用groupjoin左联接的linq版本:

from c in classes
join ljsc in studentClasses 
     on c.id equals ljsc.classId 
     into leftjoinStudentClasses
from sc in leftjoinStudentClasses.DefaultIfEmpty(new StudentClass())
join ljs in students 
     on sc.studentId equals ljs.id 
     into leftjoinStudents
from s in leftjoinStudents.DefaultIfEmpty(new Student())
group new { s,c } by c.name into grp
select new 
{
    @class = grp.Key, students = from ss in grp select ss?.s?.name
}

Link to dotnetfiddle version

答案 1 :(得分:0)

尝试

Class.Select(c => new ClassStudentDto 
{ 
  ClassName = c.Name, 
  StudentNames = new List<string>(Student.Where(s => StudentClass.Where(cs => cs.ClassId == c.Id).Select(cs => cs.StudentId).Contains(s.Id)).Select(s => s.Name)) 
}).ToList();

答案 2 :(得分:0)

如果您必须拥有<script type="text/javascript"> jQuery(function($) { $('select').on('change', function() { var url = $(this).val(); if (url) { window.location = url; } return false; }); }); </script> ,则可以使用:

null

但是如果您没有问题,可以取消测试:

var data = from c in context.GetClass
           join sc in context.GetStudentClasses on c.Id equals sc.ClassId into scj
           select new StudentClassDTO {
               ClassName = c.Name,
               StudentNames = scj.Any() ? (from sc in scj
                                           join s in context.GetStudents on sc.StudentId equals s.Id
                                           select s.Name).ToList()
                                        : null
           };