Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort a collection by datetime in c#

Tags:

c#

sorting

I have a List that I need to sort by DateTime, the class MyStuff looks like:

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.

like image 621
user195968 Avatar asked Oct 24 '09 19:10

user195968


People also ask

How do you sort collections in C#?

Sort(IComparer) This method is used to sort the elements in the entire ArrayList using the specified comparer. This method is an O(n log n) operation, where n is Count; in the worst case, it is an O(n^2) operation. Syntax: public virtual void Sort (IComparer comparer);

Can you sort a list in C#?

Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.


1 Answers

You seem to be working with a List<T> object, in which case the most efficient (and a simple) method would be the following:

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

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.

myList = myList.OrderBy(x => x.Created).ToList(); 
like image 161
Noldorin Avatar answered Oct 13 '22 07:10

Noldorin