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

Posted 叶长种-.Net软件工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linq和ef关于group by取最大值的两种写法相关的知识,希望对你有一定的参考价值。

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取最大值的两种写法的主要内容,如果未能解决你的问题,请参考以下文章

EF LINQ Group By 和 Sum

关于MYSQL group by 分组按时间取最大值的实现方法!

mysql通过group by分组取最大时间对应的数据,提供两种有效方法。

EF Linq to Sql 多表left join查询并对结果group by分组之后进行count,max等处理

关于max()/min()和group by 的坑

如何取group by后最大值所对应的字符字段?