以下 sql 查询的 linq 等价物是什么

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

上使用 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);

假设 SelectedProducts 是一个产品 ID 数组(整数):

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

原因:SQL IN 运算符在 LINQ 到 SQL 中的实现相反。该问题突出了 LINQ 开发人员尝试从 SQL 翻译时的一个常见错误,期望使用 [attribute] [operator] [set] 语法。

使用抽象集合语言,我们可以突出语法差异

  • SQL 使用 "Element is included in Set" 语法
  • LINQ 使用 "Set contains Element" 语法

因此必须使用 Contains 运算符还原任何 IN 子句。无论如何它都会翻译成 attribute IN (SET)

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);