简体   繁体   中英

How to get maximum version of record from each set using LINQ?

I have the following student list:

IList<Student> studentList = new List<Student>()
{ 
    new Student() { StudentID = 1, StudentName = "John", Age = 13 ,Version = 1, Group = 1},
    new Student() { StudentID = 2, StudentName = "Moin", Age = 21 ,Version = 2, Group = 1},
    new Student() { StudentID = 3, StudentName = "Bill", Age = 18, Version = 1, Group = 2},
    new Student() { StudentID = 4, StudentName = "Ram", Age = 20, Version = 1, Group = 3},
    new Student() { StudentID = 5, StudentName = "Ron", Age = 15, Version = 1, Group = 5},
    new Student() { StudentID = 6, StudentName = "yim", Age = 25, Version = 2, Group = 5},
};

How do I get a list which contains the maximum version of each group? What is the suitable LINQ query?

The output should look like:

{ StudentID = 2, StudentName = "Moin", Age = 21, Version = 2, Group = 1 },
{ StudentID = 3, StudentName = "Bill", Age = 18, Version = 1, Group = 2 },
{ StudentID = 4, StudentName = "Ram", Age = 20, Version = 1, Group = 3 },
{ StudentID = 6, StudentName = "yim", Age = 25, Version = 2, Group = 5 },

How about

var results = studentList.GroupBy(x => x.Group)
                         .Select(x => x.OrderByDescending(xx => xx.Version).First())
                         .ToList();

Group them by Group , then order the groupings by the Version descending, and grab the first off the grouping.

 var maxStudents = (from s in studentList
                    group s by s.Version into g
                    select new 
                    {
                      Version = g.Key,
                      MaxAge = g.Max(s => s.Age)
                    }).ToList();
// You'll be left with an array like: [{Version=1, MaxAge=21},...]

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