Skip to main content
 首页 » 编程设计

c#之在 ListT> 上使用 Rectangle.Intersection 进行查询

2024年02月20日11txw1958

我有一个包含矩形的类,我用这些对象填充了一个列表。这是我正在尝试做的一个例子:

class Foo  
{  
   Rectangle rect;  
   public Foo(Rectangle r) { rect = r; } 
} 
 
List<Foo> listFoo = new List<Foo>(); 
// Call the next three Rectangles 'A' 'B' and 'C'. 
listFoo.Add(new Foo(new Rectangle(0, 0, 5, 5)));    // Rect 'A' intersects with B 
listFoo.Add(new Foo(new Rectangle(3, 3, 5, 5)));    // Rect 'B' intersects with A & C 
listFoo.Add(new Foo(new Rectangle(6, 6, 5, 5)));    // Rect 'C' intersects with B 
 
var query = ???; 
 
foreach (Rectangle r in query)  
{  
    // Should give two results 
    // Rectangle(3, 3, 2, 2);   A & B 
    // Rectangle(6, 6, 2, 2);   B & C 
} 

我能否编写一个查询,使用 Rectangle.Intersect() 返回 listFoo 中唯一交集的列表,而没有来自 .Intersect(A,B) 和 .Intersect(B,A) 之类的重复项?

请您参考如下方法:

 var q = (from f1 in listFoo 
          from f2 in listFoo 
          let r = Rectangle.Intersect(f1.rect,f2.rect) 
          where f1 != f2 && r != Rectangle.Empty 
          select r).Distinct();