2021年1月5日星期二

C# linq max by then by

I would like to group a list of data per a key, and find the max per a different property. If there is a tie, I would find the max among the ties by another property.

public class Model  {      public int Id { get; set; }      public string GroupKey { get; set; }      public string MaxKey { get; set; }  }    /********** DATA ***************/  Id        GroupKey        MaxKey         1         groupA          a                2         groupA          b                3         groupB          c                4         groupB          c                

I would like to get the models with the below Ids:

  • 2 because within groupA, 2 has a bigger MaxKey of b
  • 4 because within groupB, both 3 and 4 have the same MaxKey of c but 4 has a bigger Id

What I have now is:

from model in list  group model by model.GroupKey into grouped  select new  {      Key = grouped.Key,      Max = grouped.Max(g => g.MaxKey)  }  

I am not sure how to do the 2nd max in the syntax. Can anyone please help?

Constraints:

  1. The code needs to be able to run in the database.
  2. Please do not use the expression syntax.
https://stackoverflow.com/questions/65588605/c-sharp-linq-max-by-then-by January 06, 2021 at 08:37AM

没有评论:

发表评论