How do I sort this structure correctly?
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);
You can use lambda expressions as well as generics here:
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);
Another popular solution is Linq, but it creates a new list and so could be not that efficient:
People = People.OrderBy(x => x.Age).ToList();
x.Age - y.Age could overflow if the Ages have opposite signs, so x.Age.CompareTo(y.Age) might be better.
Personis a mutable struct which some people consider evil.