Home > Software engineering >  Find the max element in array field in the list of objects
Find the max element in array field in the list of objects

Time:05-28

Suppose I have a class Student with simple definition:

public string Name { get; set; }
public int[] Marks { get; set; }

Now I create a list of students:

List<Student> students = new List<User>();
students.Add(new Student("John", { 3, 4, 5, 5, 4 }));
students.Add(new Student("Adam", { 2, 5, 5, 1, 3 }));
students.Add(new Student("Katy", { 6, 3, 2, 2, 3 }));

Now, I need to create a LINQ query which will retrieve the best single mark among all of the students. In this case, it would be 6, because this is the highest value from all the arrays. I came up with something like this:

var query =
    from student in students
    where student.Marks is not null
    group student by student.Marks into studentMarks
    group studentMarks.Key.Max() by studentMarks.Key.Max() into studentMarks
    orderby studentMarks.Key descending
    select studentMarks.Key;

Console.WriteLine(query.ElementAt(0)); // output: 6

Now, how can I write it in a better way, so that it just outputs single int, so I can simply say:

Console.WriteLine(query);

CodePudding user response:

Use SelectMany:

int topMark = students.SelectMany(s => s.Marks).Max()  // 6

CodePudding user response:

retrieve the best single mark among all of the students

Use Max query

var query = students.Max(s => s.Marks.Max());
Console.WriteLine(query);
  • Related