Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the max element in array field in the list of objects

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

>Solution :

Use SelectMany:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading