2

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);
2
  • 1
    Person is a mutable struct which some people consider evil. Commented Mar 16, 2014 at 13:06
  • Please, do not include information about a language used in a question title unless it wouldn't make sense without it. Tags serve this purpose. Commented Mar 16, 2014 at 13:18

4 Answers 4

5

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();
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for stating that LINQ creates a new list. This is important when lots of records are involved.
x.Age - y.Age could overflow if the Ages have opposite signs, so x.Age.CompareTo(y.Age) might be better.
2

You can use LINQ's OrderBy method:

var sortedPeople = People.OrderBy(x => x.Age)

Comments

1
var sortedPeople = People.OrderBy(p => p.Age)

Comments

0
List<Person> res = People.OderBy(x => x.Age).ToList();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.