Where in 子句使用 linq
Where in clause using linq
尝试将具有 2 级 where in 子句的查询转换为 linq 并出现一些错误。有人可以帮我解决这个问题吗?
原始查询:
select id
from student
where suId
in (select suId
from subjects
where cid
in (select id
from chapters
where chapter='C203'))
LINQ 查询:
var query = (from s in dc.students
let subs = (from su in dc.subjects
where su.cid == Convert.ToInt32(from c in dc.Chapters
where c.chapter == 'Ç203'
select c.id) //Single chapter id will be returned
select su.suid)
where subs.Contains(s.sid)
select s.id).ToArray();
编译应用程序时出现低于 2 个错误
- 'System.Linq.IQueryable' 不包含 'Contains' 的定义并且最佳扩展方法重载 'System.Linq.ParallelEnumerable.Contains(System.Linq.ParallelQuery, TSource)' 有一些无效参数
- 实例参数:无法从 'System.Linq.IQueryable' 转换为 'System.Linq.ParallelQuery'
由于 Linq
是延迟加载所有内容,因此您不需要将所有内容都塞进一个语句中;你可以这样做:
var chapterIds = dc.Chapters
.Where(c => c.Chapter == "C023")
.Select(c => c.Id);
var subjectIds = dc.Subjects
.Where(s => chapterIds.Contains(s.Cid))
.Select(s => s.Suid);
var students = dc.Students
.Where(s => subjectIds.Contains(s.Suid))
.Select(s => s.Sid)
.ToArray();
这样您就可以通过查看每个子查询的内容来调试每个子查询returns。
但是,查看您原来的 select,您可以将整个内容重写为 Join
并消除错误问题:
var students = dc.Chapters.Where(c => c.Chapter == "C023")
.Join(dc.Subjects,
c => c.Id,
s => s.Cid,
(chapter, subject) => subject)
.Join(dc.Students,
subj => subj.Suid,
student => student.Suid,
(subj, st) => st.Sid)
.ToArray();
尝试将具有 2 级 where in 子句的查询转换为 linq 并出现一些错误。有人可以帮我解决这个问题吗?
原始查询:
select id
from student
where suId
in (select suId
from subjects
where cid
in (select id
from chapters
where chapter='C203'))
LINQ 查询:
var query = (from s in dc.students
let subs = (from su in dc.subjects
where su.cid == Convert.ToInt32(from c in dc.Chapters
where c.chapter == 'Ç203'
select c.id) //Single chapter id will be returned
select su.suid)
where subs.Contains(s.sid)
select s.id).ToArray();
编译应用程序时出现低于 2 个错误
- 'System.Linq.IQueryable' 不包含 'Contains' 的定义并且最佳扩展方法重载 'System.Linq.ParallelEnumerable.Contains(System.Linq.ParallelQuery, TSource)' 有一些无效参数
- 实例参数:无法从 'System.Linq.IQueryable' 转换为 'System.Linq.ParallelQuery'
由于 Linq
是延迟加载所有内容,因此您不需要将所有内容都塞进一个语句中;你可以这样做:
var chapterIds = dc.Chapters
.Where(c => c.Chapter == "C023")
.Select(c => c.Id);
var subjectIds = dc.Subjects
.Where(s => chapterIds.Contains(s.Cid))
.Select(s => s.Suid);
var students = dc.Students
.Where(s => subjectIds.Contains(s.Suid))
.Select(s => s.Sid)
.ToArray();
这样您就可以通过查看每个子查询的内容来调试每个子查询returns。
但是,查看您原来的 select,您可以将整个内容重写为 Join
并消除错误问题:
var students = dc.Chapters.Where(c => c.Chapter == "C023")
.Join(dc.Subjects,
c => c.Id,
s => s.Cid,
(chapter, subject) => subject)
.Join(dc.Students,
subj => subj.Suid,
student => student.Suid,
(subj, st) => st.Sid)
.ToArray();