broke
broke

Reputation: 8302

LINQ to Entities: nullable datetime in where clause

I have a where clause that looks up child objects on an entity:

var Lookup = row.Offenses.Where(x => x.Desc == co.Desc && x.Action == co.Action && x.AppealYN == co.AppealYN && x.OffDate == co.OffDate).ToList();

Sometimes the co.OffDate can be null, which will cause an exception. Right now, the only way I can think of to get around that, is to use an if statement:

 if (co.OffDate.HasValue)
                                {
 var Lookup = row.Offenses.Where(x => x.Desc == co.Desc && x.Action == co.Action && x.AppealYN == co.AppealYN && x.OffDate == co.OffDate).ToList();
                                }
                                else
                                {
                                     var Lookup = row.Offenses.Where(x => x.Desc == co.Desc && x.Action == co.Action && x.AppealYN == co.AppealYN).ToList();
                                }

Is there anyway I can re-write the linq query to accomplish what the if statement does? I still want to do a lookup, even if the co.OffDate is null.

Upvotes: 3

Views: 8760

Answers (2)

Drew Shafer
Drew Shafer

Reputation: 4802

You could insert a ternary into your Where filter:

var Lookup = row.Offenses
  .Where(x => 
    x.Desc == co.Desc 
    && x.Action == co.Action 
    && x.AppealYN == co.AppealYN 
    && (co.OffDate.HasValue ? x.OffDate == co.OffDate : true)
  ).ToList();

Upvotes: 8

Erik Philips
Erik Philips

Reputation: 54638

I would rewrite it to be more readable (in my opinion):

var query = row.Offenses.Where(x => x.Desc == co.Desc 
                                    && x.Action == co.Action 
                                    && x.AppealYN == co.AppealYN)
if (co.OffenseDate.HasValue)
{
  query = query.Where(x.OffDate == co.OffenseDate);
}

var Lookup = query.ToList();

Upvotes: 3

Related Questions