Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 以下sql查询的linq等价物是什么_C#_Sql_Linq - Fatal编程技术网

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

C# 以下sql查询的linq等价物是什么,c#,sql,linq,C#,Sql,Linq,我试过这个: select Productid from categories where `categoryname` in `('abc','def','ghi')`; 但这似乎不起作用 您需要在所选产品上使用Contains 使用方法表示法 var res = from catg in db.Categories where SelectedProducts.Contains(catg.categoryname) select catg.Productid; 假设SelectedP

我试过这个:

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

但这似乎不起作用

您需要在所选产品上使用
Contains

使用方法表示法

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

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

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

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

  • SQL使用“元素
    包含在集合中”语法
  • LINQ使用“Set
    contains
    Element”语法

因此,必须使用
Contains
运算符还原
子句中的任何
。无论如何,它将转换为(SET)中的
属性。

中的SQL与:

还是兰姆达

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

您的SQL语句说的是
categoryname
,但LINQ说的是
CategoryId
-这是有意的吗?var res=来自catg in db.Categories,其中catg.categoryname.ToString()包含(SelectedProducts)选择catg;在这种情况下,LINQ和SQL不一致,它们做不同的事情。请参阅关于如何在LINQ中复制IN语句的两个答案。我对CategoryID.ToString()感到困惑-如果它是一个整数,那么与整数列表相比,您的性能会更好。请参阅@smartDev答案
var res = db.Categories.Where(catg => SelectedProducts
            .Contains(catg.categoryname)).Select(catg.Productid);
var cats = db.Categories.Where(o => SelectedProducts.Contains(o.CategoryId));
var pids = cats.Select(o => o.ProductId);
var res = from catg in db.Categories 
          where new[] {"abc","def","ghi"}.Contains(catg.categoryname) 
          select catg.Productid
db.Categories.Where(x => new[] {"abc","def","ghi"}.Contains(x.categoryname)).Select(c => c.ProductId);