Are these two linq queries of the same performance? And How to implement .Any in linq query?
for example, the following composite query + method looks not good enough. I am seeking for better approach.
foreach (var x in A)
{
foreach (var y in B)
{
if (getLazyList(x, y).Any(z => z == y))
{
blacklist.Add(x)开发者_JAVA技巧;
break;
}
}
}
Now compared to this one provided by: @Bob Vale
var q = from x in A
from y in B
where getLazyList(x,y).Contains(y)
select x;
blacklist.AddRange(q);
would 2nd method do the unnecessary loops? in 1st example i use .any() and break to escape the inner loop, how would linq handle this in 2nd case?
Here's a slightly different LINQ reimplementation of your loops:
blacklist.AddRange(A.Where(x => B.Any(y => getLazyList(x, y).Any(z => z == y))));
how about this;
var q = from x in A
from y in B
where getLazyList(x,y).Contains(y)
select x;
blacklist.AddRange(q);
if AddRange doesn't work then just replace the last line with
foreach (var x in q) blacklist.Add(x);
To handle the break you'd have to use an any clause
var q = from x in A
where B.Any(y=>getLazyList(x,y).Contains(y))
select x
The for
loops in the two snippets will perform identically, and the only difference is the use of Contains
vs Any
.
This question LINQ Ring: Any() vs Contains() for Huge Collections discusses the difference between the two operators.
Typically Contains
should be no slower than Any
, but will probably execute in the same time.
The difference is that Contains
will evaluate using the implementation of Equals
, whereas Any
accepts a delegate.
精彩评论