tags:

views:

83

answers:

5

Hi,

I have a List<MyClass> and I want to sort it by DateTime CreateDate attribute of MyClass.

Is that possible with LINQ ?

Thanks

+3  A: 

You can enumerate it in sorted order:

IEnumerable<MyClass> result = list.OrderBy(element => element.CreateDate);

You can also use ToList() to convert to a new list and reassign to the original variable:

list = list.OrderBy(element => element.CreateDate).ToList();

This isn't quite the same as sorting the original list because if anyone still has a reference to the old list they won't see the new ordering. If you actually want to sort the original list then you need to use the List<T>.Sort method.

Mark Byers
How can I put the latest on top ? by asc ?
Kubi
`OrderByDescending` instead of `OrderBy`
Mark Byers
+1. superb, thanks for posting this.
adrianos
+1  A: 

Here is a sample:

using System.Collections.Generic;
using System.Linq;

namespace Demo
{ 
    public class Test
    {
        public void SortTest()
        {
            var myList = new List<Item> { new Item { Name = "Test", Id = 1, CreateDate = DateTime.Now.AddYears(-1) }, new Item { Name = "Other", Id = 1, CreateDate = DateTime.Now.AddYears(-2) } };
            var result = myList.OrderBy(x => x.CreateDate);
        }
    }

    public class Item
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public DateTime CreateDate { get; set; }
    }
}
anthonyv
"Have you tried using linq?" LOL - that's what the question is about!
Aaronaught
Ya that was a typo... lol
anthonyv
A: 

Sure the other answers with .OrderBy() work, but wouldn't you rather make your source item inherit from IComparable and just call .Sort()?

Jarrett Meyer
+5  A: 

To sort the existing list:

list.Sort((x,y) => x.CreateDate.CompareTo(y.CreateDate));

It is also possible to write a Sort extension method, allowing:

list.Sort(x => x.CreateDate);

for example:

public static class ListExt {
    public static void Sort<TSource, TValue>(
            this List<TSource> list,
            Func<TSource, TValue> selector) {
        if (list == null) throw new ArgumentNullException("list");
        if (selector == null) throw new ArgumentNullException("selector");
        var comparer = Comparer<TValue>.Default;
        list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
    }
}
Marc Gravell
+1 for showing this
Kubi
A: 
       class T  {
            public DateTime CreatedDate { get; set; }
        }

to use:

List<T> ts = new List<T>(); 
ts.Add(new T { CreatedDate = DateTime.Now }); 
ts.Add(new T { CreatedDate = DateTime.Now }); 
ts.Sort((x,y) => DateTime.Compare(x.CreatedDate, y.CreatedDate));

Preet Sangha