[英]Writing a subquery using LINQ in C#
I would like to query a DataTable that produces a DataTable that requires a subquery. 我想查询一个DataTable,它生成一个需要子查询的DataTable。 I am having trouble finding an appropriate example.
我找不到合适的例子。 This is the subquery in SQL that I would like to create:
这是我想要创建的SQL中的子查询:
SELECT *
FROM SectionDataTable
WHERE SectionDataTable.CourseID = (SELECT SectionDataTable.CourseID
FROM SectionDataTable
WHERE SectionDataTable.SectionID = iSectionID)
I have the SectionID, iSectionID and I would like to return all of the records in the Section table that has the CourseID of the iSectionID. 我有SectionID,iSectionID,我想返回Section表中具有iSectionID的CourseID的所有记录。
I can do this using 2 separate queries as shown below, but I think a subquery would be better. 我可以使用2个单独的查询来完成此操作,如下所示,但我认为子查询会更好。
string tstrFilter = createEqualFilterExpression("SectionID", strCriteria);
tdtFiltered = TableInfo.Select(tstrFilter).CopyToDataTable();
iSelectedCourseID = tdtFiltered.AsEnumerable().Select(id => id.Field<int>("CourseID")).FirstOrDefault();
tdtFiltered.Clear();
tstrFilter = createEqualFilterExpression("CourseID", iSelectedCourseID.ToString());
tdtFiltered = TableInfo.Select(tstrFilter).CopyToDataTable();
Although it doesn't answer your question directly, what you are trying to do is much better suited for an inner join: 虽然它没有直接回答你的问题,但你想要做的更适合内部联接:
SELECT *
FROM SectionDataTable S1
INNER JOIN SectionDataTable S2 ON S1.CourseID = S2.CourseID
WHERE S2.SectionID = iSectionID
This then could be modeled very similarily using linq: 然后可以使用linq非常类似地建模:
var query = from s1 in SectionDataTable
join s2 in SectionDataTable
on s1.CourseID equals s2.CourseID
where s2.SectionID == iSectionID
select s1;
When working in LINQ you have to think of the things a bit differently. 在LINQ工作时,你必须对事情有所不同。 Though you can go as per the Miky's suggestion.
虽然你可以按照Miky的建议去。 But personally I would prefer to use the Navigational properties.
但我个人更喜欢使用Navigational属性。
For example in your given example I can understand that you have at-least 2 tables, 例如,在您给出的示例中,我可以理解您至少有2个表,
One Section must contain a Course reference 一节必须包含课程参考
Which means 意思是
One Course can be in multiple Sections 一门课程可以分为多个部分
Now if I see these tables as entities in my model I would see navigational properties as, 现在,如果我在模型中看到这些表作为实体,我会看到导航属性为,
Course.Sections //<- Sections is actually a collection
Section.Course //<- Course is an object
So the same query can be written as, 所以相同的查询可以写成,
var lstSections = context.Sections.Where(s => s.Course.Sections.Any(c => c.SectionID == iSectionID)).ToList();
I think you main goal is, you are trying extract all the Sections
where Courses
are same as given Section
's Courses
. 我想你的主要目标是,你正在试图提取所有的
Sections
,其中Courses
都相同,若Section
的Courses
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.