How to write LINQ IN clause query which will work as LIKE operator as well?

Paul picture Paul · May 24, 2012 · Viewed 7.9k times · Source

How we can write a LINQ query for following select sql query:

string brandid="1,2,3"
string bodystyleid="1,2,3"
-------------------
-----------------

select * from car
where brandid in (brandid)
and bodystyleid in (brandid)
----------------------
-------------------

My specific requirement is that if brandid or bodystyleid is blank(if user does not select any checkbox of a particular search option) query should return all record for that particular where condition.

Please guide me.

Thanks,

Paul

Answer

Richard picture Richard · May 24, 2012

In order to fulfil your requirement about returning all items if none are specified, you need to check for the lists being empty.

var brands = brandid.Split(',').Select(x => Int32.Parse(x));
var styles = bodystyleid.Split(',').Select(x => Int32.Parse(x));

var result = from c in car
             where (!brands.Any() || brands.Contains(c.brandid))
                  && (!styles.Any() || styles.Contains(c.bodystyleid))
             select c;

(similar to sgmoore's solution, but includes the check for no brand/style specified)

I've not actually checked how this gets converted back to SQL - it may be more efficient to use a flag to indicate whether there are any values:

var brands = ....;   // As above
bool anyBrands = brands.Any()
var result = from c in car
             where (!anyBrands || brands.Contains(c.brandid))
               .....