I have a List<T>
How can I sort it ascendingly by one of T's int property?
I'm aware that I could create my own method to this manually but is there any way to this concisely like List<T>.Sort
( by T's int property ); ?
I have a List<T>
How can I sort it ascendingly by one of T's int property?
I'm aware that I could create my own method to this manually but is there any way to this concisely like List<T>.Sort
( by T's int property ); ?
you can use Enumerable Orderby to sort by it's property.
List<yourType> yourCollection = YourSourceList.OrderBy(e=>e.YourProperty).ToList();
Yes, you can use List<T>.Sort
:
list.Sort((t1, t2) => t1.IntProperty.CompareTo(t2.IntProperty));
A less efficient but more readable approach is using Enumerable.OrderBy
:
list = list.OrderBy(t => t.IntProperty).ToList();
Hey Try This code to your list for sorting ASC/DESC
List<HRDocumentCheckList> ser=new List<HRDocumentCheckList>();
ser.OrderByDescending(q => q.Document.Id).ToList();
Hope it helps you
For folks who doesn't have the privilege to use Lamda expression approach, which was accepted as answer can follow the below given approach. The core idea is to implement IComparable<Person>
whereby checking any specific property/field defined within object and here it is 'Person
'.
public class ConsoleApp
{
private static void Main(string[] args)
{
List<Person> p = new List<Person>();
p.Add(new Person() {Age = 25, Name = "Jo"});
p.Add(new Person() {Age = 10, Name = "Jo"});
p.Add(new Person() {Age = 2, Name = "Jo"});
p.Sort();
}
}
public class Person : IComparable<Person>
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Person other)
{
return other == null ? 1 : Age.CompareTo(other.Age);
}
}