Dev
Dev

Reputation: 13

Lambda expression Where by second column if first column is null. c#

I have the example data.

Name      CreatedDate      UpdatedDate
---------------------------------------
Tony      10/10/2021       10/10/2022
David     NULL             10/10/2022

I just want to get data by CreatedDate field less than today, if CreatedDate field was null, I will get by UpdatedDate field.

var data = ...Where(x => x.CreatedDate.HasValue ? x.CreatedDate.Value : UpdatedDate < today)

Is that expression correct?

Hope everyone can help me.

Upvotes: 1

Views: 85

Answers (1)

pm100
pm100

Reputation: 50180

I assume that CreatedDate is of type Date? (ie nullable so that HasValue works) so this slight tweak is needed, plus added parens for clarity

Where(x=> (x.CreatedDate.HasValue ? x.CreatedDate.Value : x.UpdatedDate) < today)

Always assuming 'today' has a valid date in it.

Upvotes: 1

Related Questions