[英]What is the linq equivalent of the below sql query
select Productid from categories where `categoryname` in `('abc','def','ghi')`;
我試過這個:
var res = from catg in db.Categories where catg.CategoryId.ToString().Contains(SelectedProducts) select catg;
但這似乎不起作用......
假設SelectedProducts
是一個產品ID數組(整數):
var cats = db.Categories.Where(o => SelectedProducts.Contains(o.CategoryId));
var pids = cats.Select(o => o.ProductId);
原因:SQL IN
運算符在LINQ
to SQL中相反實現。 這個問題突出了LINQ開發人員試圖從SQL轉換的一個常見錯誤,期望[attribute] [operator] [set]
語法。
使用抽象集語言,我們可以突出顯示語法差異
is included
在Set中”語法 contains
Element”語法 因此必須使用Contains
運算符還原任何IN
子句。 無論如何它將轉換為attribute IN (SET)
。
您需要在SelectedProducts上使用Contains
var res = from catg in db.Categories where
SelectedProducts.Contains(catg.categoryname) select catg.Productid;
使用方法表示法
var res = db.Categories.Where(catg => SelectedProducts
.Contains(catg.categoryname)).Select(catg.Productid);
SQL IN與IEnumerable.Contains()的等價性:
var res = from catg in db.Categories
where new[] {"abc","def","ghi"}.Contains(catg.categoryname)
select catg.Productid
或者lambda
db.Categories.Where(x => new[] {"abc","def","ghi"}.Contains(x.categoryname)).Select(c => c.ProductId);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.