Entity framework selects rows with maximum value for one column

I have a table with about 20 columns. I want to get rows with all columns with the maximum column "version" for each identifier.

ID      | Version | Other data
--------+---------+----------
1       | 1       | text1
1       | 2       | text2
1       | 3       | text3
2       | 1       | text1
3       | 1       | text1
3       | 2       | text2

I want to:

ID      | Version | Other data
--------+---------+----------
1       | 3       | text3
2       | 1       | text1
3       | 2       | text2

I know how to do this in sql. I do not know how to do this on the basis of essence. Especially if I have 20 columns.

+4
source share
2 answers
context.TableName
    .GroupBy(x=>x.ID)
    .Select(x=>new 
    {
        ID = x.Key, 
        row = x.Where(r=>r.Version == x.Max(m=>m.Version)).FirstOrDefault()})
    .Select(x=>new {x.ID, x.row.Version, x.row.OtherData});
+1
source

I created my own version, but it's slow

context.TableName.GroupBy(group=> group.recipeID)
                        .SelectMany(
                            group=>
                                group.Where(
                                    r=> r.version == group.Max(x => x.version))
                                    .Select(r=> r));
0
source

All Articles