【问题标题】:In Linq, how to find if a set contains an element without using Count(predicate)?在 Linq 中,如何在不使用 Count(predicate) 的情况下查找集合是否包含元素?
【发布时间】:2010-07-19 09:04:08
【问题描述】:

由于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 查找集合中是否包含符合条件的项目,而不必遍历集合中的每个元素并计算匹配的数量?

【问题讨论】:

    标签: c# linq linq-to-sql optimization exists


    【解决方案1】:

    你可以试试

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

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

    【讨论】:

    • 它有效。 sql查询为select (case when exists(...) then 1 else 0 end)。谢谢。
    【解决方案2】:

    如果你想检查一个条件,你可以使用下面的代码

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      • 2016-10-19
      相关资源
      最近更新 更多