简体   繁体   中英

Linq involving groupby orderby and join

I have two tables

tblEquipment            
Id1 Id2 Version1 Version2         
1    1     -        0          
2    1     A        1            
3    1     B        1         
4    1     B        2         
5    2     -        0                                               
6    2     A        0

and another table

tblHistory                 
IdParent     Version1    Version2        Date             
1               -           0           1/01/14            
1               A           1           2/01/14              
1               B           1           3/01/14              
1               B           2           4/01/14                 
2               -           0           4/01/14                
2               A           0           6/01/14           
2               A           0           8/01/14

I am trying to write a query that fetches the record which has the maximum Version1 and Version2 corresponding to the maximum version1. For eg I want the following records from the above table -

Id2 = 1 , Version1 = B , Version2 = 2 and Date = 4/01/14
Id2 = 2 , Version1 = A , Version2 = 0 and Date = 8/01/14

Can anyone help me with the linq that gives me the above result.

Fetching data according the rule you described would be like this:

var result = history
            .GroupBy( h => h.IdParent )
            .Select( h => h.OrderBy( h1 => h1.Version1 )
                             .ThenBy( h2 => h2.Version2 )
                             .Last() )
            .Select(h => new { 
                        Id2 = h.IdParent, 
                        Version1 = h.Version1, 
                        Version2 = h.Version2, 
                        Date = h.Date 
                        } 
            );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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