JL.
JL.

Reputation: 81262

Linq: sort items in a collection based on DateTime field

I have a collection of Task objects in a list.

List<Tasks> tasks = getTasks(); //This populates tasks

Each task item has a "dateCreated" field which is a fully fledged DateTime field.

Public class Task
{
    DateTime dateCreated {get;set;}
    //other props
}

My question is once I have a list of tasks, how can I resort the items in the collection based on this dateCreated field.

  1. Best case scenario is if I could resort the existing collection
  2. If this isn't possible then using Linq select items based on DateCreated, and populate another collection.

Thanks in advance.

Upvotes: 0

Views: 1319

Answers (3)

asem mokllati
asem mokllati

Reputation: 235

best way to do that is

tasks = tasks.OrderBy(t => t.DateCreated.Ticks).ToList();

in this way list will be ordered by date and time

Upvotes: 0

Dean Chalk
Dean Chalk

Reputation: 20451

You dont need to implement IComparable<T> to sort a list:

tasks.Sort((t1,t2) => t1.DateCreated.CompareTo(t2.DateCreated));

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190907

You can implement IComparable<T> and use List<T>.Sort().

Or you could:

tasks.Sort(t => t.DateCreated);

http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx

If you don't want to do that, just do:

tasks = tasks.OrderBy(t => t.DateCreated).ToList();

Upvotes: 3

Related Questions