views:

79

answers:

1

Hi,

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?

+13  A: 

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.

Anton
It works. Sql query is `select (case when exists(...) then 1 else 0 end)`. Thank you.
MainMa