开发者

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

开发者 https://www.devze.com 2023-03-06 23:53 出处:网络
Given a class as follows: public class Student { public int Age { get;开发者_如何学C set; } public int Score { get; set; }

Given a class as follows:

public class Student
{
  public int Age { get;开发者_如何学C 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#.


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


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)


// 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];  
0

精彩评论

暂无评论...
验证码 换一张
取 消