Linq: How to Exclude Condition If Parameter Is Null

Excluding Condition if Parameter is null

Sure it is:

public List<Pallet> GetPallet(string palletID, string locationID)
{
List<Pallet> data = new List<Pallet>();
data = data.Where(x => x.PalletID == palletID && (locationID == null || x.LocationID == locationID)).ToList();

return data;
}

LINQ WHERE statement/ignore conditions

You can add it as a condition:

 var query= from x in context.a 
where String.IsNullOrEmpty(param1) || (x.p == param1 && x.i == param2)
select x;

If param1 is null or empty, the condition will always be true, which effectively "ignores" the where conditions entirely.

Linq remove where if the value is null

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.

Linq-to-SQL: Ignore null parameters from WHERE clause

your issue is that your are not passing in a nullable int, you are passing in a null.

try this:

Print(null);

private void Print(int? num)
{
Console.WriteLine(num.Value);
}

and you get the same error.

It should work if you do this:

var q = ( from c in db.Contacts
where
c.Active == true
&&
c.LastReviewedOn <= DateTime.Now.AddDays(-365)
&&
( // Owned by group
ownerGroupIds.Count == 0 ||
ownerGroupIds.Contains( c.OwnerGroupId.Value )
)
select c );

if(ownerUserId != null && ownerUserId.HasValue)
q = q.Where(p => p.OwnerUserId.Value == ownerUserId.Value);

return q.Count();

foreach with where and condition if parameter exists

You could put an OR condition allowing an item to pass if one of the search parameters is null or empty. Something like:

innerJoinQuery.Where(item => 
(string.IsNullOrWhiteSpace(StudentName) || item.StudentName == StudentName)
&&
(string.IsNullOrWhiteSpace(StudentSurname) || item.StudentSurname == StudentSurname)
)


Related Topics



Leave a reply



Submit