Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq remove where if the value is null

That My Linq query

var result = db.APPLICATIONS
.Where(a => Statuses.Contains(a.STATUS_ID))
.Where(a => a.TrackingNo == TrackingNo)

Statuses is a int list and TrackingNo is a nullable int (int?).

Problem: If the TrackingNo is null then i dont want to run this clause or just skip this condition.

like image 881
Mateen -ul-haq Avatar asked Jan 06 '23 17:01

Mateen -ul-haq


1 Answers

LINQ queries can be built in multiple steps:

var result = db.APPLICATIONS
    .Where(a => Statuses.Contains(a.STATUS_ID));

if (TrackingNo != null)
{
    result = result.Where(a => a.TrackingNo == TrackingNo);
}

Note that if you have a Select (a projection), you probably must build the query in multiple steps in multiple variables:

var result2 = result.Select(a => new { a.STATUS_ID });

with the result2 "built" after the if.

like image 191
xanatos Avatar answered Jan 17 '23 15:01

xanatos