How to sort List<T> by object property in C#?
Hello everyone! I just started learning C# and encountered a problem when sorting a list of objects.
I have a `Person` class with `Name` and `Age` fields. I create a list of people and want to sort it by age (from youngest to oldest). Here is my code:
```csharp
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List people = new List
{
new Person { Name = "Anna", Age = 25 },
new Person { Name = "Boris", Age = 30 },
new Person { Name = "Victor", Age = 20 }
};
// Trying to sort, but don't know how
people.Sort(); // Error: doesn't know how to compare Person
```
I understand that `Sort()` doesn't know which field to sort by. I tried using `OrderBy`, but couldn't figure it out either. Please advise how to do it correctly.
No answers yet.
Log in to leave an answer