开发者

In Linq, how to find if a set contains an element without using Count(predicate)?

开发者 https://www.devze.com 2023-01-07 16:44 出处:网络
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:

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?


You could try

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

Not sure if that uses an if exists, but you can try and see what is sent.


If you are trying to check a condition you can use the following code

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

but if you want to check if any rows exist without any condition like p.ProductID == 1234 you should do the following

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

精彩评论

暂无评论...
验证码 换一张
取 消