2012-01-20 217 views
2

我有以下模式:與許多專業 專業與許多參團度嵌套選擇在LINQ

學校(或只是度短)。

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

我不太確定我知道如何返回每個不同專業的學位。

回答

1

我能夠通過檢查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

簡單地進行組通過

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 }); 
} 
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電話。

+0

嗨,亞當,謝謝你。由於我能夠爲學校獲得所有不同的專業,這變得非常接近。我仍然難倒的地方是我想返回像[UCLA],[[Computer Science],[B,M,D]]。我不知道該怎麼做,是在找回不同的專業後返回不同的學位。 – khaihon