开发者

Sorting a List of Class with LINQ

I have a List<MyClass> 开发者_高级运维and I want to sort it by DateTime CreateDate attribute of MyClass.

Is that possible with LINQ ?

Thanks


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


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.


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; }
    }
}


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜