如何正确排序此结构?
struct Person
{
public string Name;
public int Age;
}
List<Person> People = new List<Person>();
// Add several hundred records
// sort by age
People.Sort(Person.Age);
答案 0 :(得分:3)
您可以在此处使用 lambda表达式以及泛型:
struct Person {
public string Name;
public int Age;
}
// generic List<T> is much better than deprecated List
List<Person> People = new List<Person>();
...
People.Sort((x, y) => x.Age - y.Age);
另一个流行的解决方案是 Linq ,但它创建了一个新列表,因此可能效率不高:
People = People.OrderBy(x => x.Age).ToList();
答案 1 :(得分:2)
您可以使用LINQ的OrderBy
method:
var sortedPeople = People.OrderBy(x => x.Age)
答案 2 :(得分:1)
var sortedPeople = People.OrderBy(p => p.Age)
答案 3 :(得分:0)
List<Person> res = People.OderBy(x => x.Age).ToList();