Linq无聊练习系列5--OrderBy ,Groupby练习

 /**************OrderBy ,Groupby练习*******************/
           
            //按学生的总分数按降序排列排序
            var list = from s in ctx.T_Student
                       join c in ctx.T_Score
                       on s.stuNumber
                       equals c.stuNumber
                       into temp
                       from t in temp
                       orderby temp.Sum(k => k.score) descending
                       select new {
                        stuName = s.stuName,
                        scoreSum = temp.Sum(k=>k.score)
                       };
            //对学生的年龄和姓名进行排序
            var list1 = from s in ctx.T_Student
                       orderby s.stuSex,s.stuName descending
                       select s;
            //对于上边的可以用lambda进行简化
            var list2 = ctx.T_Student.OrderBy(s => s.stuAge).ThenBy(k=>k.stuName);
            //也可以用连续的orderBy进行排序,不过级联方式是逆序,上边的list2可以这样表示
            var list3 = ctx.T_Student.OrderBy(s => s.stuName).OrderBy(k=>k.stuAge);
            //对orderby排序要注意的地方是只能对基本数据类型进行排序,不能对类型,以及匿名类进行排序,否则的话会抛异常

            //每门课程分数最高的分数,并按课程号进行排序
            var list4 = from s in ctx.T_Score
                        group s by s.courceNumber
                            into g
                            orderby g.Key
                            select new
                            {
                                courceNumber = g.Key,
                                coreForCourse = from f in g
                                                where f.score == g.Max(n => n.score)
                                                select f
                            };
            //下面着重对groupby进行案列练习,对分数按课程号进行分组
            var list5 = from s in ctx.T_Score
                        group s by s.courceNumber
                            into temp1
                            select temp1;
            //每门课程的最高分数
            var list6 = from s in ctx.T_Score
                        group s by s.courceNumber
                            into temp1
                            select new {
                                courseNumber = temp1.Key,
                                maxCourece = temp1.Max(k=>k.score)
                            };
            //分组的条件也可以是自定义的表达式,如下
            var list7 = from s in ctx.T_Score
                        group s by s.score + 10
                            into g
                            select g;

            //也可以对多列进行分组
            var list8 = from s in ctx.T_Score
                        group s by new
                        {
                            s.courceNumber,
                            s.stuNumber
                        } into g
                        select new {
                            g.Key,
                            g
                        };

原文地址:https://www.cnblogs.com/selfimprove/p/3603758.html