简体   繁体   中英

What is the linq equivalent of the below sql query

select Productid from categories where `categoryname` in `('abc','def','ghi')`; 

I have tried this:

var res = from catg in db.Categories where catg.CategoryId.ToString().Contains(SelectedProducts) select catg;

But this doesnt seem to work...

Assuming SelectedProducts is an array of product ids (integers):

var cats = db.Categories.Where(o => SelectedProducts.Contains(o.CategoryId));
var pids = cats.Select(o => o.ProductId);

Reason: SQL IN operator is implemented oppositely in LINQ to SQL. The question highlights a common mistake in LINQ developers trying to translate from SQL, expecting an [attribute] [operator] [set] syntax.

Using an abstract set language we can highlight syntax differences

  • SQL uses a "Element is included in Set" syntax
  • LINQ uses a "Set contains Element" syntax

So any IN clause must be reverted using the Contains operator. It will translate to attribute IN (SET) anyways.

You need to use Contains on SelectedProducts

var res = from catg in db.Categories where 
SelectedProducts.Contains(catg.categoryname) select catg.Productid;

Using method notation

var res = db.Categories.Where(catg => SelectedProducts
            .Contains(catg.categoryname)).Select(catg.Productid);

The equivalence of a SQL IN with IEnumerable.Contains() :

var res = from catg in db.Categories 
          where new[] {"abc","def","ghi"}.Contains(catg.categoryname) 
          select catg.Productid

Or lambda

db.Categories.Where(x => new[] {"abc","def","ghi"}.Contains(x.categoryname)).Select(c => c.ProductId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM