1

I stucked at somewhere while developing our system. I have 2 different datetime columns DateModified and DateCreated. I want to sort my data according to those 2 columns at the same time. Like;

Id Name   DateCreated    DateModified
--------------------------------------------------------
1 Ali         2015-01-01       2015-02-02
2 Veli          2015-01-02       2015-02-03
3 Mehmed          2015-02-01       2015-02-05
4 Ahmed           2015-02-04        null

When I want to make a descending order by for those data, it should give me the result of

3 Mehmed
4 Ahmed
2 Veli
1 Ali

So... What is the way of doing that? Thanks

fatih
  • 154
  • 1
  • 8
  • 1
    possible duplicate of [Multiple "order by" in LINQ](http://stackoverflow.com/questions/298725/multiple-order-by-in-linq) – markpsmith Apr 14 '15 at 11:48

3 Answers3

4

From what I understand you want the result to be sorted by both dates as a single property, not using ThenBy right?

Not a LINQ expert but I think this should work:

var Result = Items.OrderBy(x=> x.DateModified==null ? x.DateCreated : x.DateModified);

EDIT:

This goes on the assumption that the modify date is always after the creation date. In an general case it would look like this:

var Result = Items.OrderBy(x=> x.A >= x.B ? x.A : x.B);
GregoryHouseMD
  • 1,726
  • 1
  • 13
  • 34
2

use OrderBy and ThenBy

var Result = Items.OrderBy(x => x.DateModified).ThenBy(x => x.DateCreated);
fubo
  • 39,783
  • 16
  • 92
  • 127
0

If Ahmed is second, then you can use DateCreated instead of null: Items.OrderBy(a => a.DateModified != default(DateTime?) a.DateModified: a.DateCreated);

Marcin J
  • 368
  • 4
  • 15