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#.
Order by Score then by Age.
var result1 = listStd.OrderBy(arg => arg.Score).ThenBy(arg => arg.Age);
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];
精彩评论