在 Linq 中,如何在不使用 Count(predicate) 的情况下查找集合是否包含元素?
由于 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 issues
。
如何通过 Linq 查找集合中是否包含与条件匹配的项目,而无需遍历集合中的每个元素并计算匹配的数量?
Since IEnumerable.Contains()
method does not accept a predicate as an argument, Most people use the following code to check the existence of something matching a condition:
// ProductId is unique.
if (Products.Count(c => c.ProductId = 1234) == 1)
{
// Products list contains product 1234.
}
This code forces to walk through every product and to check if it matches. There is really no need to do so.
When looking at Linq-to-SQL generated SQL code, there is the same problem. A select count(*) ... where ProductId = @p0
statement is sent, instead of if exists
.
How is it possible through Linq to find if a set contains an item which matches a condition, without having to walk through every element in a set and count the number of matches?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试
不确定是否使用 if 存在,但您可以尝试查看发送的内容。
You could try
Not sure if that uses an if exists, but you can try and see what is sent.
如果您尝试检查条件,可以使用以下代码,
但如果您想检查是否存在任何没有任何条件(如 p.ProductID == 1234)的行,您应该执行以下操作
If you are trying to check a condition you can use the following code
but if you want to check if any rows exist without any condition like p.ProductID == 1234 you should do the following