码迷,mamicode.com
首页 > 其他好文 > 详细

linq和ef关于group by取最大值的两种写法

时间:2019-12-19 18:50:52      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:==   nbsp   rank   toolbar   use   strong   www   response   string   

LINQ:

 
var temp = from p in db.jj_Credentials
                       group p by p.ProfessionID into g
                       select new
                       {
                           g.Key,
                           MaxPrice = g.Max(p => p.CredentialsRankID)
                       };
 

EF:

var temp1 = db.jj_Credentials.GroupBy(m => m.ProfessionID).Select(m => m.Max(o => o.CredentialsRankID));
            foreach(var p in temp1)
            {
                Response.Write(p);
            }

补充:取最大值后取得当前完整记录的方法,两种写法:

写法1

 
//写法1
            var list1 = db.jj_Credentials.Where(m => m.UserId == UserContext.UserID && m.IsAudit).OrderByDescending(m => m.CredentialsRankID).ToList().GroupBy(x => x.ProfessionID)
                .SelectMany(t => t.Select((b, i) => new { b, i }).Where(m => m.i == 0)).Select(m => m.b);
            
            foreach (var i in list1)
            {
                Response.Write(string.Format("{0} {1} {2} {3}<br>", i.CredentialsID, i.UserId, i.CredentialsRankID, i.ProfessionID));
            }
 

写法2

 
//写法2
            var list = db.jj_Credentials.Where(m => m.UserId == UserContext.UserID && m.IsAudit).OrderByDescending(x => x.CredentialsRankID).ToList().GroupBy(x => x.ProfessionID)
            .Select(g => new { g, count = g.Count() })
            .SelectMany(t => t.g.Select(b => b).Zip(Enumerable.Range(1, t.count), (j, i) =>
                new
                {
                    CredentialsID = j.CredentialsID,
                    UserID = j.UserId,
                    CredentialsRankID = j.CredentialsRankID,
                    ProfessionID = j.ProfessionID,
                    rn = i
                }).Where(x => x.rn == 1));

            //打印
            foreach (var i in list)
            {
                Response.Write(string.Format("{0} {1} {2} {3}<br>", i.CredentialsID, i.UserID, i.CredentialsRankID, i.ProfessionID));
            }
 

linq和ef关于group by取最大值的两种写法

标签:==   nbsp   rank   toolbar   use   strong   www   response   string   

原文地址:https://www.cnblogs.com/xxjs/p/12069345.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!