I have a List that I need to sort by DateTime, the class MyStuff looks like:
我有一个List,我需要按DateTime排序,类MyStuff看起来像:
public class MyStuff
{
public int Type {get;set;}
public int Key {get;set;}
public DateTime Created {get;set;}
}
I need to be able to sort the collection List by the Created (DateTime) field.
我需要能够通过Created(DateTime)字段对集合List进行排序。
2 个解决方案
#1
71
You seem to be working with a List<T>
object, in which case the most efficient (and a simple) method would be the following:
您似乎正在使用List
myList.Sort((x, y) => DateTime.Compare(x.Created, y.Created));
This uses the overload of the List.Sort method than takes a Comparison<T>
delegate (and thus lambda expression).
这使用了List.Sort方法的重载,而不是使用Comparison
You can of course use the LINQ OrderBy
extension method, but I don't think this offers any advantages, and can be significantly slower, depending on your situation.
您当然可以使用LINQ OrderBy扩展方法,但我认为这不会带来任何好处,并且可能会明显变慢,具体取决于您的具体情况。
myList = myList.OrderBy(x => x.Created).ToList();
#2
6
var query =
from m in mystuffcollection
orderby m.Created ascending
select m;
#1
71
You seem to be working with a List<T>
object, in which case the most efficient (and a simple) method would be the following:
您似乎正在使用List
myList.Sort((x, y) => DateTime.Compare(x.Created, y.Created));
This uses the overload of the List.Sort method than takes a Comparison<T>
delegate (and thus lambda expression).
这使用了List.Sort方法的重载,而不是使用Comparison
You can of course use the LINQ OrderBy
extension method, but I don't think this offers any advantages, and can be significantly slower, depending on your situation.
您当然可以使用LINQ OrderBy扩展方法,但我认为这不会带来任何好处,并且可能会明显变慢,具体取决于您的具体情况。
myList = myList.OrderBy(x => x.Created).ToList();
#2
6
var query =
from m in mystuffcollection
orderby m.Created ascending
select m;