0

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 ); ?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Mikk
  • 455
  • 1
  • 13
  • 19

6 Answers6

6

you can use Enumerable Orderby to sort by it's property.

List<yourType> yourCollection = YourSourceList.OrderBy(e=>e.YourProperty).ToList();
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83
  • 2
    @TimSchmelter thanks for your feed back. I changed it. it's not LINQ. it's simple Enumerable class. – Ravi Gadag May 07 '13 at 11:25
  • `Enumerable.OrderBy` and `ToList` are Linq methods and `ToList` creates a new `List` even if there's already one. The purpose of `List.Sort` (or `Array.Sort`) is to avoid creating an new collecton because that doubles the required memory(temporarily): – Tim Schmelter May 07 '13 at 11:27
  • @TimSchmelter that i know. ToList() creates new one. Sort() will do alter in the same List. so Sort is Efficient. – Ravi Gadag May 07 '13 at 11:28
  • 2
    Linq is what's sitting in it's namespace and `Enumerable` is part of the `System.Linq` namespace. It's `Linq-To-Objects`. – Tim Schmelter May 07 '13 at 11:34
5

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();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

Try this:

 List<T> lst=List<T>.OrderBy(x => x.Property).ToList();
Praveen VR
  • 1,554
  • 2
  • 16
  • 34
1

You could write your own Comparer class. And then sort using that class e.g:

myList.Sort(new MyListComparer());
PHP Rocks
  • 176
  • 1
  • 3
0

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

Neeraj Dubey
  • 4,401
  • 8
  • 30
  • 49
0

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);
        }
    }
S.N
  • 4,910
  • 5
  • 31
  • 51