Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.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# 在Linq中,如何在不使用Count(谓词)的情况下查找集合是否包含元素?_C#_Linq_Linq To Sql_Optimization_Exists - Fatal编程技术网

C# 在Linq中,如何在不使用Count(谓词)的情况下查找集合是否包含元素?

C# 在Linq中,如何在不使用Count(谓词)的情况下查找集合是否包含元素?,c#,linq,linq-to-sql,optimization,exists,C#,Linq,Linq To Sql,Optimization,Exists,由于IEnumerable.Contains()方法不接受谓词作为参数,因此大多数人使用以下代码检查是否存在与条件匹配的内容: // ProductId is unique. if (Products.Count(c => c.ProductId = 1234) == 1) { // Products list contains product 1234. } 此代码强制遍历每个产品并检查其是否匹配。真的没有必要这样做 在查看Linq到SQL生成的SQL代码时,也存在同样的问题。

由于
IEnumerable.Contains()
方法不接受谓词作为参数,因此大多数人使用以下代码检查是否存在与条件匹配的内容:

// ProductId is unique.
if (Products.Count(c => c.ProductId = 1234) == 1)
{
    // Products list contains product 1234.
}
此代码强制遍历每个产品并检查其是否匹配。真的没有必要这样做

在查看Linq到SQL生成的SQL代码时,也存在同样的问题。A
选择计数(*)。。。其中ProductId=@p0
语句被发送,而不是
(如果存在)

如何通过Linq查找集合中是否包含与条件匹配的项,而不必遍历集合中的每个元素并计算匹配数?

您可以尝试

if (Products.Any(c => c.ProductId = 1234))
{
//do stuff
}

不确定是否使用if exists,但您可以尝试查看发送的内容。

如果您尝试检查某个条件,则可以使用以下代码

if(Products.Any(p => p.ProductID == 1234))
{
    //do sth
}
但是如果您想检查是否存在没有任何条件的行,比如p.ProductID==1234,您应该执行以下操作

if(Products.Any(p => p != null))
{
//do sth
}

它起作用了。Sql查询是
select(存在时为case(…),然后为1 else 0 end)
。非常感谢。