LINQ 挑出每组里面的最大值 最小值的记录

//Lambda
//思路是分组之后,得分按照降序排列,拿到得分等于每组第一个的值
 List<ResultPointGroup> newResultPointSeq3 = newResultPointGroup.GroupBy(item => item.GroupNum)
               .Select(p => p.OrderByDescending(o => o.Score).ElementAt(0)).ToList();
//SQL 早期的思想,挑出最大值和组号,再左连接回去,过滤掉右表没有的
            List<ResultPointGroup> newResultPointSeq4 = (from item in newResultPointGroup
                                                         group item by item.GroupNum into resultGroup
                                                         select new ResultPointGroup
                                                         {
                                                             GroupNum = resultGroup.Key,
                                                             Score = (from item2 in resultGroup
                                                                      select item2.Score).Max(),
                                                         }).ToList();
            List<ResultPointGroup> newResultPointSeq5 = (from item in newResultPointGroup
                                                         join item2 in newResultPointSeq4
                                                         on new { join1 = item.GroupNum, join2 = item.Score } equals new { join1 = item2.GroupNum, join2 = item2.Score }
                                                         where item2 != null
                                                         select new ResultPointGroup
                                                         {
                                                             X = item.X,
                                                             Y = item.Y,
                                                             Score = item.Score,
                                                             TemplateName = item.TemplateName
                                                         }).ToList();
//利用LINQ里面的let,赋值一个每组的最大值,再select一次即可
            List<ResultPointGroup> newResultPointSeq6 = (from item in newResultPointGroup
                                                         group item by item.GroupNum into resultGroup
                                                         let maxScore = (from item3 in resultGroup
                                                                         select item3.Score).Max()
                                                         from item2 in newResultPointGroup
                                                         where item2.Score.Equals(maxScore) 
                                                         && item2.GroupNum.Equals(item.GroupNum)
                                                         select item2
                                                         ).ToList();

你可能感兴趣的:(linq,sql,数据库)