1

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);
                    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?

colinfang
  • 20,909
  • 19
  • 90
  • 173

3 Answers3

2

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))));

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
1

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
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
  • would it do the unnecessary loops? in my example i use `.any()` and `break` to escape the inner loop, how would linq handle this in ur case? – colinfang Aug 26 '11 at 00:21
  • @colinfang Yes it would do unessary loops, I didn't notice the break sorry. Contains should be as efficient as any and depending on the collection more efficient in some cases. Depends if you are only doing an equals comparison. – Bob Vale Aug 26 '11 at 08:24
  • yes, i didn't realize the `contain` would do, and the test shows a major improvement after I switch to `contain`. – colinfang Aug 26 '11 at 08:46
0

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.

Community
  • 1
  • 1
Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169