q0987
q0987

Reputation: 36002

C# -- How to sort a List and find the smallest element in it?

Given a class as follows:

public class Student
{
  public int Age { get; set; }
  public int Score { get; set; }

  public Student() {}
  public Student(int age, int score)
  {
     Age = age;
     Score = score;
  }
  ...

}

List<Student> listStd;

Question 1> How to sort Student first by score then by age in ascending order?

Question 2> How to find the Student with least score and then smallest age?

I know how to do all these in C++ and I want to know the alternative way in C#.

Upvotes: 0

Views: 4145

Answers (3)

LukeH
LukeH

Reputation: 269658

// sort Student first by score then by age in ascending order
listStd.Sort((x, y) => {
                           int i = x.Score.CompareTo(y.Score);
                           if (i == 0)
                               i = x.Age.CompareTo(y.Age);

                           return i;
                       });

// find the Student with least score and then smallest age
var leastAndSmallest = listStd[0];  

Upvotes: 0

Akrem
Akrem

Reputation: 4652

order by age

List<Student> byage = listStd.OrderBy(s => s.Age).ToList();

order by score

List<Student> score = listStd.OrderBy(s => s.score).ToList();

least score

var least_score = listStd.SingleOrDefault(arg => arg.score == listStd.Max(arg => arg.score )

smallest age

var smallest_age = listStd.SingleOrDefault(arg => arg.Age == listStd.Min(arg => arg.Age)

Upvotes: 0

Alex Aza
Alex Aza

Reputation: 78537

  1. Order by Score then by Age.

    var result1 = listStd.OrderBy(arg => arg.Score).ThenBy(arg => arg.Age);
    
  2. You can't do both least age and score. As those can be two different Students.

    var result2 = listStd.FirstOrDefault(arg => arg.Age == listStd.Min(arg => arg.Age));
    

unless you want the least score between the youngest students:

var youngestStudents = listStd.Where(arg => arg.Age == listStd.Min(arg => arg.Age)).ToList();
var result2 = youngestStudents.FirstOrDefault(arg => arg.Score == listStd.Min(arg => arg.Score));

Upvotes: 2

Related Questions