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.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is how to sort a class list by integer property in C#:
C#
In this example, we first create a class called
Personwith an integer property calledAge. We then create a list ofPersonobjects 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 theAgeproperty. 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 passtrueas the second parameter to theSort()method.