c# - How to compare each element with every other in LINQ? -


the problem is, ienumerable of rectangles need know each rectangle whether intersects of others. output sequence same count containing 1 boolean value every rectangle.

so kind of nested loop problem should not compare element , if rect intersects rect b there no need check rect b again.

is possible linq?

//for every rectangle in list.  //search list, eliminating same one,  //and find if of others intersect it. var intersectingrectangles = rectangles   .where(rect => rectangles                  .where(r => r != rect)                  .any(r => dointersect(rect, r))); 

this assumes have function dointersect taking 2 rectangles , telling if intersect.

there many improvements made if not effecient enough needs. potentially sort based on coordinates , able eliminate lot of comparisons. but, depends on data looks , how fast needs be.

if want have output contain each of original ienumerable along status whether intersects others switch using select() below.

var allwithintersectionstatus = rectangles.select(rect => new {     value = rect,     doesintersect = rectangles         .where(rectwhere => rectwhere != rect)         .any(rectant => dointersect(rect, rectant)) }); 

Comments