Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ WHERE statement/ignore conditions

I need to ignore some or all conditions in WHERE statement if parameter is null or empty F.E:

I have simple LINQ query

var query = from x in context.a
            where x.p == param1 && x.i == param2
            select x;

How can I ignore x.p == param1 if param1 is null or emty?

EDIT

Tried this

var query = from myLog in myContext.ApsValidationLogs
            where (myLog.systemtype == comboBoxSystemType.SelectedItem.ToString() || string.IsNullOrEmpty(comboBoxSystemType.SelectedItem.ToString()))
              && (myLog.bankid == comboBoxBankId.SelectedItem.ToString() || string.IsNullOrEmpty(comboBoxBankId.SelectedItem.ToString())))
            select myLog;

But got

Object reference not set to an instance of an object.

In case if second combobox's item is null. What's wrong?

like image 425
Ars Avatar asked Sep 17 '11 18:09

Ars


2 Answers

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.

like image 131
Reed Copsey Avatar answered Nov 20 '22 05:11

Reed Copsey


you can individually check param1 and param2 this one..

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

the above two conditions also works well , if you want to check individually

like image 34
Glory Raj Avatar answered Nov 20 '22 06:11

Glory Raj