Select max as second criteria with Linq

c# entity-framework-6 linq linq-to-entities

Question

I'm attempting to get all rows with a certain field and its maximum value.

To clarify my scepticism, I'll provide a model as an example.

class model
{
    [Key]
    [Column(Order=0)]
    public int Key { get; set; }     

    [Key]
    [Column(Order=1)]
    public int Revision { get; set; }

    public string OtherStuff { get; set; }    
}

One example of data might be

|Key|Revision   |Otherstuff |
|1  |1          |A          |
|1  |2          |B          |
|1  |3          |C          |
|2  |1          |D          |
|2  |2          |E          |
|3  |1          |F          |

What I'm looking for:

|Key|Revision   |Otherstuff |
|1  |3          |C          |
|2  |2          |E          |
|3  |1          |F          |

I attempted the options I could discover, but I was unable in getting them to work.

This is all I have.

IQueryable<model> data = dbContext.model;

data = data.GroupBy(x => x.Revision ).OrderByDescending(x => x.Key).SelectMany(x => x)

//Applying logic to filter the data 
data = data.Where(...)

It is a filtering mechanism, and while using SelectMany, the database is destroyed, making it impossible for me to continue editing the list as I need to.

What am I supposed to do?

Thanks!

Solved

data = data.GroupBy(x => x.Key).Select(x => x.OrderByDescending(d => d.Revision).FirstOrDefault());

Thanks for your replies!

1
0
8/23/2018 2:42:17 PM

Accepted Answer

var result = data.GroupBy(x => x.Revision).Select(x => x.First())

Use x.FirstOrDefault if you attempt to do any further actions (such as choosing a subset of columns) after the first query.

1
8/23/2018 2:30:45 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow