使用LINQ只获取List<>中的那些项目

时间:2016-05-23 11:54:46

标签: c# linq

我会假设有一个简单的LINQ查询来执行此操作,我只是不确定如何。请参阅下面的代码段,评论解释了我想要做的事情:

我有三张桌子

Course
   Id     Name
  ----   ------
    1     php
    2     joomla
    3     mysql  

MainCourse
  Id     CourseCode
 ----   -------------
  1       Foundation
  2       Diploma
  3       Professional

SubCourse
  Id  CourseId   MainCourseId  
 ---- --------- --------------   
   1     1             1
   2     1             2
   3     2             2
   4     1             3
   5     2             3
   6     3             3

  List<int> courseIdList={1,2}

//I would like to perform a LINQ query to give me 'CourseCode'
//from 'courseIdList' 
//this example should give me 'Diploma'
//CourseIdList could vary below are the expected results
//CourseIdList={1}  ==> CourseCode=Foundation(MainCourse)
//CourseIdList={1,2} ==> CourseCode=Diploma(MainCourse)
//CourseIdList={1,2,3} ==> CourseCode=Professional(MainCourse)

//Rule is that I want to get only those items from the subcourse
//where 'courseId(subcourse)' matches the 'courseIdList'

//Say CourseIdList={1,2},I need to omit the following Id (1,4,5,6)
//from subcourse since MainCourseId=1 , contains courseId =1 (not 1,2)
//and MainCourseId=3 , contains courseId = 1,2,3 (not 1,2)

1 个答案:

答案 0 :(得分:0)

因此,您可以通过SubCourseMainCourseId进行分组,然后创建相应课程ID的列表,并将此列表与courseIdList进行比较。

一个简单的例子:

var result = subCourses.GroupBy(sc => sc.MainCourseId).
               Where(g => g.Select(c => c.CourseId).SequenceEqual(courseIdList));

但请注意,SequenceEquals仅在序列顺序相同时才有效。因此,您需要稍微增强此Where子句,以比较可能不在同一顺序中的序列。

如果您的courseIdList始终是有序的,那么订购这样的课程ID序列就足够了:

var result = subCourses.GroupBy(sc => sc.MainCourseId).
               Where(g => g.Select(c => c.CourseId).OrderBy(id => id).SequenceEqual(courseIdList));

您获得的resultIEnumerable<IGrouping<SubCourse>>,其中包含由MainCourses中引用的Courses组成的所有对应courseIdList(理论上可能还有更多)匹配MainCourseKey的{​​{1}}是IGrouping