Oleg Sh
Oleg Sh

Reputation: 9013

EF : order by 2 fields when they are not null

I have an entity with fields:

public partial class Load 
{
    public DateTime CreatedOn { get; set; }
    public DateTime? UpdatedOn { get; set; }
}

I have to order records (DESC) by following way: If UpdatedOn has value then "look at" this value, else look at CreatedOn value. How to do it?

Upvotes: 2

Views: 466

Answers (1)

go..
go..

Reputation: 948

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand look here

 items.OrderBy(x => x.UpdatedOn ?? x.CreatedOn);

OR

 items.OrderByDescending(x => x.UpdatedOn ?? x.CreatedOn);

Upvotes: 6

Related Questions