LINQ中的嵌套选择

本文关键字:选择 嵌套 LINQ | 更新日期: 2023-09-27 18:20:46

我有以下模型:

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

+------+--------+--------+
|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()
            };

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

LINQ中的嵌套选择

我能够通过检查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)
          } )
      };

非常感谢大家。

以下内容如何?

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调用。

只需通过进行分组

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 });
}