简体   繁体   English

LINQ:如何通过group by子句获取最大ID?

[英]LINQ: How to get the Max Id with a group by clause?

I am looking for a way in LINQ to get a max Id record by using 'Group By' clause 我正在寻找一种在LINQ中使用'Group By'子句获取最大ID记录的方法

Consider the following Sample data 考虑以下样本数据

  Table: ProcessAud

  ProcessSeq     ProjectSeq   ProjectValue    Active
      11              1           50000          Y
      12              1           10000          Y
      13              2           70000          Y 
      14              2           90000          Y

In which I want to get two records as a list such that is second and fourth 我想在其中获得两个记录作为列表,例如第二和第四
records (ie) ProcessSeq 12 and 14. And I tried it like following 记录(即)ProcessSeq 12和14。

var ProcessAudList = ProcessAudService.FilterBy(x => x.Active == "Y"    
  ).GroupBy(x => x.ProjectSeq).Max().ToList();

It is not working properly, So how to do it in LINQ. 它无法正常工作,因此如何在LINQ中做到这一点。 Please anybody help. 请任何人帮助。

You want to pick top record from each group. 您想从每个组中选择最高记录。

var ProcessAudList = ProcessAudService.Where(x => x.Active == "Y")
.GroupBy(x => x.ProjectSeq, (key,g)=>g.OrderByDescending(e=>e.ProjectValue).First());

Check demo code 查看演示代码

When you use GroupBy extension, method will return you IGrouping instance and you should query IGrouping instance like below; 当您使用GroupBy扩展名时,方法将返回您的IGrouping实例,您应按以下方式查询IGrouping实例;

var ProcessAudList = collection.Where(x => x.Active == "Y").GroupBy(x => x.ProjectSeq).Select(x => x.OrderByDescending(a => a.ProcessSeq).FirstOrDefault()).ToList();

Hope this helps 希望这可以帮助

You're most of the way there, but Max is the wrong term to use. 您已完成大部分工作,但使用Max是错误的用语。

Each IGrouping is an IEnumerable (or IQueryable ) sequence of its own, so you can use OrderBy and First clauses to get the answer you need: 每个IGrouping都是其自身的IEnumerable (或IQueryable )序列,因此您可以使用OrderByFirst子句来获取所需的答案:

var ProcessAudList = ProcessAudService
    .FilterBy(x => x.Active == "Y")
    .GroupBy(x => x.ProjectSeq)
    .Select(grp => grp.OrderByDescending(x => x.ProcessSeq).First())
    .ToList();

The Select clause will process each of the groups, order the groups descending by ProcessSeq and select the first one. Select子句将处理每个组,按ProcessSeq降序排列组,然后选择第一个。 For the data you provided this will select the rows with ProcessSeq equal to 12 and 14. 对于您提供的数据,这将选择ProcessSeq等于12和14的行。

With this code you can get all max id in foreach 使用此代码,您可以在foreach中获取所有最大ID

var res = from pa in ProcessAud
      group Cm by pa.ProjectSeq into Cm1
      select new
      {
           _max = Cm1.Max(x => x.ProcessSeq)
      };
foreach (var item in res)
{
    //item._max have biggest id in group
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM