thalm
thalm

Reputation: 2920

How to compare each element with every other in LINQ?

The problem is, for an IEnumerable of rectangles I need to know for each rectangle whether it intersects any of the others. So the output would be a sequence with the same count containing one boolean value for every rectangle.

So it is kind of a nested loop problem but it should not compare the element with itself and if rect A intersects rect B there is no need to check rect B again.

Is this possible with LINQ?

Upvotes: 1

Views: 1859

Answers (1)

eoldre
eoldre

Reputation: 1087

//for every rectangle in your list. 
//search the list, eliminating the same one, 
//and find if any of the others intersect with it.
var intersectingRectangles = rectangles
  .Where(rect => rectangles
                 .Where(r => r != rect)
                 .Any(r => DoIntersect(rect, r)));

This assumes that you have a function DoIntersect taking two rectangles and telling you if they intersect.

There are MANY improvements that could be made to this if it is not effecient enough for your needs. you could potentially sort based on coordinates and be able to eliminate a lot of comparisons. But, that all depends on what your data looks like and how fast this needs to be.

If you want to have the output contain each of the original IEnumerable along with a status about whether is intersects any others than switch to using a Select() as below.

var allWithIntersectionStatus = rectangles.Select(rect => new
{
    Value = rect,
    DoesIntersect = rectangles
        .Where(rectWhere => rectWhere != rect)
        .Any(rectAnt => DoIntersect(rect, rectAnt))
});

Upvotes: 2

Related Questions