嵌套在LINQ中选择

时间:2012-01-20 01:04:15

标签: c# linq entity-framework

我有以下型号:

拥有多个专业的学校 拥有多个学位的专业(或简称学位)。

+------+--------+--------+
|School| Major  | Degree |
+------+--------+--------+
| UCLA |CompSci | B      |
| UCLA |CompSci | M      |
| UCLA |CompSci | D      |
| UCLA |Math    | B      |
+------+--------+--------+

我想取回一所学校提供的所有学位,按专业分组(因此每个学位的学位不会重复)。我怎么能这样做?到目前为止,我有以下代码,但现在我被卡住了。

var query = from school in schools
            where school.Id == Id
            select new
            {
                name   = s.Name
                majors = (from major in school.Majors
                         select new
                         {
                             majorname = major.Name
                         }).Distinct()
            };

我不太确定我知道如何返回每个不同专业的学位。

3 个答案:

答案 0 :(得分:2)

我能够通过检查SO上的类似情况并使用group / by / into关键字来解决这个问题。

 var query = from school in schools
      where school.Id == id
      select new
      {
       name = school.Name,
       majors = ( from major in school.Majors
          group major.Degree by major.Name into sub
          select new
          {
           m = sub.Key,
           d = (from degree in sub
             select degree.Name)
          } )
      };

非常感谢大家。

答案 1 :(得分:1)

只需制作一个分组

var groupedBy= list.Where(c=> c.Id==Id).GroupBy(c=> c.Major);
foreach(var item in groupedBy )
{
 var v=item.Select(c=> new {Major=item.Key,Degree=c.Degree });
}

答案 2 :(得分:1)

以下情况如何?

var query = schools
    .Where(school => school.Id == Id)
    .Select(school => new
        {
            Name = school.Name,
            Majors = school.Majors.Select(major => major.Name).Distinct()
        })
    .GroupBy(obj => obj.Majors);

对代码的唯一更改是将Majors字段更改为IEnumerable<string>并添加GroupBy电话,而不是查询查询语法。