khaihon
khaihon

Reputation: 235

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.

Upvotes: 3

Views: 20791

Answers (3)

khaihon
khaihon

Reputation: 235

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.

Upvotes: 2

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23349

Simply make a Group By

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

Upvotes: 1

Adam Mihalcin
Adam Mihalcin

Reputation: 14478

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.

Upvotes: 1

Related Questions