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

时间:2010-07-19 09:04:09

标签: 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-to-SQL生成的SQL代码时,存在同样的问题。发送select count(*) ... where ProductId = @p0语句,而不是if exists

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

2 个答案:

答案 0 :(得分:14)

你可以尝试

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

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

答案 1 :(得分:1)

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

if(Products.Any(p => p.ProductID == 1234))
{
    //do sth
}

但是如果你想检查是否存在没有任何条件的行,例如p.ProductID == 1234你应该执行以下操作

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