菜的像徐坤
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

Code First 分组

4783人阅读 2021/3/29 16:03 总访问:882930 评论:0 收藏:0 手机
分类: EF

根据linq表达式

           //实例化数据
           SchoolContext schoolcontext = new SchoolContext();
           
           
           //linq表达式
            var Info = from scroe in schoolcontext.Scroe
                                   //根据ScroeName排序
                           group scroe by scroe.ScroeName into scroetemp
                           select new
                           {
                               //Key代表排序的那个字段
                               scroetemp.Key,
                               //求和
                               sum = scroetemp.Sum(a => a.ScroeNum),
                               //最大值
                               max = scroetemp.Max(a => a.ScroeNum),
                               //最小值
                               min = scroetemp.Min(a => a.ScroeNum),
                           };

根据lamdba表达式(GroupBy关键字)

 //实例化数据
 SchoolContext schoolcontext = new SchoolContext();
                                                                 
  var Info = schoolcontext.Scroe.GroupBy(a => a.ScroeName).Select(scroetemp => new {
               //Key代表排序的那个字段,多个字段排序则通过Key点出该字段(Key.ScroeName)
                ScroeName = scroetemp.Key,
                sum = scroetemp.Sum(a => a.ScroeNum),
                max = scroetemp.Max(a => a.ScroeNum),
                min = scroetemp.Min(a => a.ScroeNum),
            
            });

示例(先查询,在分组)

    //三表联查
    var Info = schoolcontext.UserInfo.Join(schoolcontext.Parents, a => a.Sid, b => b.Uid, (a, b) => new
             {
                 User = a,
                 father = b.Father,
                 mather = b.Mather
             }).Join(schoolcontext.Scroe, a => a.User.Sid, b => b.Uid, (a, b) => new
             {
                 Sid = a.User.Sid,
                 UserName = a.User.UserName,
                 Scroename = b.ScroeName,
                 Scroenum = b.ScroeNum,
                 Father = a.father,
                 Mather = a.mather
                 //根据查询的结果进行分组
             }).GroupBy(a => new { a.Sid, a.Father, a.Mather, a.UserName }).Select(temptable => new 
             {
                 Sid = temptable.Key.Sid,
                 UserName = temptable.Key.UserName,
                 Sum = temptable.Sum(a => a.Scroenum),
                 Min = temptable.Min(a => a.Scroenum),
                 Max = temptable.Max(a => a.Scroenum),
                 Avg = temptable.Average(a => a.Scroenum),
                 Father = temptable.Key.Father,
                 Mather = temptable.Key.Mather,
             }).ToList();

排序  升序(OrderBy)降序(OrderByDescending)

//升序(OrderBy
Info = Info.OrderBy(a => a.Sum).ToList();
//降序(OrderByDescending)
Info = Info.OrderByDescending(a => a.Sum).ToList();


评价