LINQ Nested Selects

c# entity-framework linq

Question

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.

1
3
1/20/2012 1:04:15 AM

Accepted Answer

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.

2
1/23/2012 11:57:41 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow