2

I have two for loops to remove item from the list. I am looking for an equivalent LINQ statement for these loops

for (Int32 i = points.Count - 1; i >= 0; i--)
{
    for (Int32 j = touchingRects.Count - 1; j >= 0; j--)
    {
        if (touchingRects[j].HitTest(points[i], rect.TopEdge.Y1))
        {
            points.RemoveAt(i);
        }
    }
}

So far I am able to do this but the compiler doesn't understand this code:

points.RemoveAll(p => touchingRects.Where(r => r.HitTest(p, r.TopEdge.Y1)));

Any help will be appreciated.

1
  • Please gives the compiler error that you are receiving.
    – Guvante
    Jun 13, 2013 at 23:14

1 Answer 1

6

The delegate that you pass into RemoveAll needs to return a bool.

I think you what to do this:

points.RemoveAll(p => touchingRects.Any(r => r.HitTest(p, r.TopEdge.Y1)));

Or possibly this (if the variable rect is actually defined elsewhere):

points.RemoveAll(p => touchingRects.Any(r => r.HitTest(p, rect.TopEdge.Y1)));

I should point out that your original code has the potential for some very strange behavior. After you remove an item from the list in your inner loop, you continue looping through touchingRects with the same index i. This can lead to some unexpected results. There probably should be a break in there somewhere, but you may have omitted from your question it for brevity. In any case, using this code fixes that problem.

1
  • Not working! The count of points is same before and after this statement. Jun 13, 2013 at 23:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.