不在第二节列表<>对象

时间:2014-08-19 02:20:18

标签: c# linq

我正在尝试创建这样的查询:

select * from Subjects
where subjectid not in ( select subjectid from results)

为此我有一个查询结果表的对象

 var _results = 
     new List<C_MiscObjects.obj_Results>();
 _results = _Enrollment.GetResultView(Convert.ToInt16(lblSid.Text), lblCourseid.Text);

第二个对象在

下面
List<CoursesDetail> _CD = _Enrollment.GetSubjects(lblCourseid.Text);

现在想要过滤_results中_CD的记录。即

! _CD.subjectid.contains( _results.subjectid)

3 个答案:

答案 0 :(得分:0)

<强> SQL:

select * from Subjects
where subjectid not in ( select subjectid from results)

<强> LINQ:

var query= Subjects.Where(s=>
                   !results.Select(r=>r.subjectid).Contains(s.subjectid));

答案 1 :(得分:0)

你想要这样的东西:

 _CD.Where(c => !_results.Select(r => r.subjectid).Contains(c.subjectid))

答案 2 :(得分:0)

SQL查询本身可以根据两个表之间的左连接重写:

select * from subjects s
left join results r on s.subjectid = r.subjectid
where r.subjectid is null

转换为LINQ,这变为:

var filtered = _CD
            .GroupJoin(_results, x => x.subjectid, y => y.subjectid, (x,y) => new {x,y})
            .SelectMany(xy => xy.y.DefaultIfEmpty(), (x,y) => new {x,y})
            .Where(xy => xy.y == null)
            .Select(xy => xy.x);

Demo