Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Selects in LINQ

I have the following model:

Schools with Many Majors Majors with Many Offered Degrees (or just Degrees for Short).

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

I'd like to retrieve all the degrees offered by a school, grouped by Majors (so majors is not repeated for each degree returned). How might I do that? I have the following code so far, but now I'm stuck.

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

I'm not quite sure I know how to return the degrees for each distinct major.

like image 763
khaihon Avatar asked Aug 15 '26 20:08

khaihon


2 Answers

I was able to solve this by checking out similar situations on SO and by using the group/by/into keywords.

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

Thanks so much everyone.

like image 82
khaihon Avatar answered Aug 17 '26 10:08

khaihon


What about the following?

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

The only change to your code, other than desugaring the query syntax, is to change the Majors field to an IEnumerable<string> and to add a GroupBy call.

like image 36
Adam Mihalcin Avatar answered Aug 17 '26 10:08

Adam Mihalcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!