How to sort List<T> by object property in C#?
Hello everyone! I'm new to 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 (ascending). I've heard that you can use `List.Sort()`, but it doesn't work directly with my objects — the compiler gives an error that it cannot compare elements. Here's 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 = 30 },
new Person { Name = "Boris", Age = 25 },
new Person { Name = "Victor", Age = 35 }
};
people.Sort(); // Error: cannot compare elements
```
I understand that `Sort()` doesn't know how to compare objects
No answers yet.
Log in to leave an answer