Steve
Steve

Reputation: 4543

Highest score data with more than one result - LINQ

How to print student with highest score if there is more than one result?

var studentList = new List<Student>()
        {
            new Student(){ Id =1, FullName = "May", CourseScore = 90},
            new Student(){ Id =2, FullName = "Joe", CourseScore = 65},
            new Student(){ Id =3, FullName = "Ann", CourseScore = 50}
        };

        var stud = studentList.OrderByDescending(c => c.CourseScore).Take(1).SingleOrDefault();
        Console.WriteLine(stud.FullName);

The above query works but only if highest score has only one element. But if more than one student have the same highest score? For example, May and Ann also 90 CourseScore? How do show both May and Ann?

Upvotes: 0

Views: 156

Answers (2)

Furkan &#214;zt&#252;rk
Furkan &#214;zt&#252;rk

Reputation: 1416

Let's assume you have the following data

var studentList = new List<Student>() {
        new Student(){ Id =1, FullName = "May", CourseScore = 90},
        new Student(){ Id =2, FullName = "Joe", CourseScore = 65},
        new Student(){ Id =3, FullName = "Ann", CourseScore = 50},
        new Student(){ Id =4, FullName = "Jac", CourseScore = 90},
    };

You can try two ways

1) process time is 15 milliseconds for my pc

   var names = studentList.GroupBy(x => x.CourseScore).Select(y => new { CourseScore = y.Key, Names = string.Join(",", y.Select(x => x.FullName)) }).OrderByDescending(x => x.CourseScore).Select(x => x.Names).FirstOrDefault();
   Console.Write(names);

2) process time is 1 milliseconds for my pc

    var maxScore = studentList.Max(x => x.CourseScore);
    var names = studentList.Where(x => x.CourseScore == maxScore).Select(x => x.FullName);
    var joinedNames = string.Join(",", names);
    Console.WriteLine(joinedNames);

They both prints: "May,Jac"

Upvotes: 1

Selim Yildiz
Selim Yildiz

Reputation: 5380

You can Group items by CourseScore and select student names as following:

var stud = studentList.GroupBy(g => g.CourseScore)
                        .Select(i => new
                        {
                            CourseScore = i.Key,
                            StudentNames = String.Join(",", i.Select(s => s.FullName))
                        })
                        .OrderByDescending(o => o.CourseScore).FirstOrDefault();

Console.WriteLine(stud.StudentNames);

It will give you following result:

May,Ann

Note: If there is only one student who has highest score, it also gives you one student name.

Upvotes: 2

Related Questions