Subin Joseph
Subin Joseph

Reputation: 59

Case statement in Linq for a nullable datetime field

I have linq query with nullable datatime field which populate value based on condition.

var result=(from t1 in context.table1
            join t2 in context.table2 
            on t1.id equals t2.fieldId
            select new model1
            {
                name= t2.name,
                DateCompleted = t1.Status == "Success" 
                    ? Convert.ToDateTime(t1.CompletedDate)
                    : Null
            }).ToList();

Here DateCompleted can be nullable .If status is success then only I need Completed date.Other wise I need to show it null . Now the ": Null" portion is throwing error.

Thanks in advance Subin

Upvotes: 2

Views: 456

Answers (3)

H. Herzl
H. Herzl

Reputation: 3258

You need to use nullable date time: default(DateTime?)

Upvotes: 1

user449689
user449689

Reputation: 3154

Try the following code:

var result=(from t1 in context.table1
            join t2 in context.table2 
            on t1.id equals t2.fieldId
            select new model1
            {
                name= t2.name,
                DateCompleted = t1.Status == "Success" 
                    ? Convert.ToDateTime(t1.CompletedDate)
                    : (DateTime?) null
            }).ToList();

Upvotes: 3

Hardik Gondalia
Hardik Gondalia

Reputation: 3717

Try this

var result=(from t1 in context.table1
             join t2 in context.table2 
            on t1.id equals t2.fieldId
            select new model1
            {
             name= t2.name,
             DateCompleted = t1.Status == "Success" ? Convert.ToDateTime(t1.CompletedDate): (DateTime?)null
                                                           }).ToList();

Upvotes: 5

Related Questions