user441365
user441365

Reputation: 4024

linq order by 2 parameters

I need to order a list with linq based on 2 parameters a Boolean and a DateTime

The top of the list has to be the Booleans that are true and then ordered by DateTime

At the bottom of the list we need the Booleans that are false, also order by DateTime

How can I achieve this?

Upvotes: 1

Views: 229

Answers (3)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

you can do like this:

var result = yourList
             .OrderBy(r=> r.BooleanField)
             .ThenByDescending(r=> r.DateTimeField);

You have to do DateTime descending to get the latest one first.

For Boolean if you want sorted on true first then use OrderByDescending on it as well:

var result = yourList
                 .OrderByDescending(r=> r.BooleanField)
                 .ThenByDescending(r=> r.DateTimeField);

Upvotes: 1

Habib
Habib

Reputation: 223187

Use Enumerable.OrderBy and Enumerable.ThenBy for the second parameter, For Ordering in descending order use Enumerable.OrderByDescending and Enumerable.ThenByDescending.

For your particular case, you need true to appear first and then you want to get the records sorted by date. If you want to get latest date first, then you will need descending order. In that case your query would be:

var query = list.OrderByDescending(r => r.BoolProperty)
                .ThenByDescending(r => r.DateTimeProperty);

Considering you have List<DummyClass> like:

List<DummyClass> list = new List<DummyClass>
{
  new DummyClass() { BoolProperty = true, DateTimeProperty = DateTime.Now.AddDays(1)},
  new DummyClass() { BoolProperty = true, DateTimeProperty = DateTime.Now.AddDays(2)},
  new DummyClass() { BoolProperty = false, DateTimeProperty = DateTime.Now.AddDays(3)},
  new DummyClass() { BoolProperty = false, DateTimeProperty = DateTime.Now.AddDays(-1)},

};

Where DummyClass is defined as:

public class DummyClass
{
    public bool BoolProperty { get; set; }
    public DateTime DateTimeProperty { get; set; }
}

For output you can use:

foreach (var item in query)
{
    Console.WriteLine("Bool {0}, DateTime {1}" , item.BoolProperty, item.DateTimeProperty);
}

Output would be:

Bool True, DateTime 09/05/2014 1:18:53 PM
Bool True, DateTime 08/05/2014 1:18:53 PM
Bool False, DateTime 10/05/2014 1:18:53 PM
Bool False, DateTime 06/05/2014 1:18:53 PM

Upvotes: 1

Tim S.
Tim S.

Reputation: 56536

For the boolean, you want a descending order (false compares like it's smaller than true). To add additional ordering parameters, you use ThenBy (for dates: oldest on top)/ThenByDescending (for dates: newest on top). I think the methods you're looking for are OrderByDescending and ThenBy.

myList.OrderByDescending(x => x.MyBool).ThenBy(x => x.MyDateTime)

Upvotes: 1

Related Questions