//输出体重最大的同学,并要求最大体重得大于39,并按照体重大下,对分组结果进行排序。 var result = from query in linq.Student group query by query.ClassID into gS where gS.Max(s => s.StudentWeigth) > 39 orderby gS.Max (s => s.StudentWeigth) descending select new { ClassID = gS.Key, MaxWeight = gS.Max (s => s.StudentWeigth) }; var result = from query in linq.Student group query by query.ClassID into gS let mw = gS.Max (s => s.StudentWeigth) where mw > 39 select new { ClassID = gS.Key, MaxWeight = mw }; foreach (var item in result) { Response.Write(string.Format("classid = {0} studentmaxweight = {1}", item.ClassID, item.MaxWeight)); }
//查询身高大于132并且体重大于30的Student,并按照StudentID升序排序,按照classID降序排序var query = from s in db.Students where s.HeightInCm > 132 && s.WeightInKg > 30 orderby s.StudentID ascending, s.ClassID descending select s;
//对Student表按照ClassID和Hometown两个字段进行分组,并输出每个班级中某个地方的学生数var query = from s in db.Students group s by new { s.ClassID, s.Hometown } into gS let cn = gS.Count() select new { ClassID = gS.Key.ClassID, Hometown = gS.Key.Hometown, Count = cn }; foreach (var item in query) { Console.WriteLine("class id = {0} hometown {1} student count = {2}", item.ClassID, item.Hometown,item.Count); }
//在上面的基础上加一点点需求,要求分组后的结果按照count排序var query = from s in db.Students group s by new { s.ClassID, s.Hometown } into gS let cn = gS.Count() orderby cn descending select new { ClassID = gS.Key.ClassID, Hometown = gS.Key.Hometown, Count = cn };