Skilled in SEO, content writing, and digital marketing. Completed several years of working in many organizations including multinational companies. I love to learn new things in life that keep me motivated.
Sure, here is how to sort a class list by integer property in C#:
C#
class Person {
public int Age { get; set; }
}
List<Person> people = new List<Person>();
people.Add(new Person { Age = 10 });
people.Add(new Person { Age = 20 });
people.Add(new Person { Age = 30 });
// Sort the list by the Age property.
people.Sort(delegate (Person p1, Person p2) {
return p1.Age - p2.Age;
});
In this example, we first create a class called Person with an integer property called
Age. We then create a list of Person objects and add three objects to the list. The first object has an age of 10, the second object has an age of 20, and the third object has an age of 30.
Next, we use the Sort() method to sort the list by the Age property. The
Sort() method takes a delegate as its parameter. The delegate is a function that takes two objects of the same type and returns an integer. In this case, the delegate compares the ages of the two objects and returns the difference.
The Sort() method will sort the list in ascending order by default. If you want to sort the list in descending order, you can pass
true as the second parameter to the Sort() method.
Liked By
Write Answer
How to sort class list by integer property?
Join MindStick Community
You have need login or register for voting of answers or question.
Aryan Kumar
19-Aug-2023Sure, here is how to sort a class list by integer property in C#:
C#
In this example, we first create a class called
Person
with an integer property calledAge
. We then create a list ofPerson
objects and add three objects to the list. The first object has an age of 10, the second object has an age of 20, and the third object has an age of 30.Next, we use the
Sort()
method to sort the list by theAge
property. TheSort()
method takes a delegate as its parameter. The delegate is a function that takes two objects of the same type and returns an integer. In this case, the delegate compares the ages of the two objects and returns the difference.The
Sort()
method will sort the list in ascending order by default. If you want to sort the list in descending order, you can passtrue
as the second parameter to theSort()
method.