Linq问题,无法获得预期的数据C#

时间:2018-05-24 07:10:35

标签: c# linq

我有List<Student>个对象,数据如下

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    public int SchoolYearId { get; set; }
    public int ClassId { get; set; }
}

&安培;数据我有这个

    public List<Student> StudentData()
    {
       return new List<Student>
       {
         new Student
         {
             StudentId=100,
             Name="Shubham",
             SchoolYearId=2016,
              ClassId=1000
         },
         new Student
         {
          StudentId=100,
          Name="Shubham",
          SchoolYearId=2017,
          ClassId=1001    
         },
         new Student
         {
          StudentId=100,
          Name="Shubham",
          SchoolYearId=2018,
          ClassId=1002
          },

         new Student
         {
           StudentId=101,
           Name="Arpit",
           SchoolYearId=2016,
           ClassId=1100
         },
        new Student
        {
          StudentId=101,
          Name="Arpit",
          SchoolYearId=2017,
         ClassId=1101
         }

       };
     }

现在我的要求是,StudentId每个学生SchoolYearId的最大值为 StudentId=100, Name="Shubham", SchoolYearId=2018, ClassId=1002 StudentId=101, Name="Arpit", SchoolYearId=2017, ClassId=1101 ,我需要学生不同。

结果我期待

session_start()

1 个答案:

答案 0 :(得分:7)

您应首先分组GroupBy),然后在每个组中计算 argmax ;唉, Linq 没有ArgMax,但可以通过Aggregate轻松模拟

var result = StudentData()
  .GroupBy(student => student.StudentId)
  .Select(group => group
     .Aggregate((s, a) => s.SchoolYearId > a.SchoolYearId ? s : a))
  .ToList(); // Let's materialize into list