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?