简体   繁体   English

Linq OrderBy 然后 GroupBy - group by 意外更改列表的顺序

[英]Linq OrderBy then GroupBy - group by unexpectedly changes order of list

When I run this expression i can see that the list order is correctly in sequence by the highest ActionId's当我运行此表达式时,我可以看到列表顺序按最高 ActionId 的顺序正确

var list = db.Actions.Where(z => z.RunId
   == RunId).OrderByDescending(w => 
    w.ActionId).ToList();

I only want to select the highest ActionId's of each ActionName so I now do:我只想选择每个ActionName 的最高 ActionId,所以我现在这样做:

var list = db.Actions.Where(z => z.RunId
 == RunId).OrderByDescending(w => 
 w.ActionId).GroupBy(c => new
         {
            c.ActionName,
            c.MachineNumber,
         })
         .Select(y => 
      y.FirstOrDefault()).ToList();

When I look at the contents of list, it hasn't selected the ActionName/MachineNumber with the highest ActionId, which I assumed would be the case by ordering then using FirstOrDefault().当我查看列表的内容时,它没有选择具有最高 ActionId 的 ActionName/MachineNumber,我认为这是通过排序然后使用 FirstOrDefault() 来实现的。

Any idea where I'm going wrong?知道我哪里出错了吗? I want to group the records by the ActionName and MachineId, and then pick the record with the highest ActionId for each group我想按 ActionName 和 MachineId 对记录进行分组,然后为每个组选择具有最高 ActionId 的记录

Instead of grouping an ordered collection, group the collection first, and then select the record with the highest ID for each of the groups.不要对有序集合进行分组,而是先对集合进行分组,然后为每个组选择具有最高 ID 的记录。 GroupBy is not guaranteed to preserve the order in each group in LINQ to SQL - it depends on your database server. GroupBy不能保证在 LINQ to SQL 中保留每个组中的顺序 - 它取决于您的数据库服务器。

var list = db.Actions.Where(z => z.RunId == RunId).GroupBy(c => new
                {
                    c.ActionName,
                    c.MachineNumber,
                })
                .Select(y => y.OrderByDescending(z => z.ActionId).FirstOrDefault()).ToList();

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

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