Home > database >  Linq OrderBy then GroupBy - group by unexpectedly changes order of list
Linq OrderBy then GroupBy - group by unexpectedly changes order of list

Time:06-14

When I run this expression i can see that the list order is correctly in sequence by the highest ActionId's

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:

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().

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

CodePudding user response:

Instead of grouping an ordered collection, group the collection first, and then select the record with the highest ID for each of the groups. GroupBy is not guaranteed to preserve the order in each group in LINQ to SQL - it depends on your database server.

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();
  • Related