所以我有一系列折线,每个折线都包含几个点。
我想从这些折线集合中获取最小和最大X,Y点,以便我可以找出包含折线的边界矩形。我如何使用LINQ做到这一点?
折线是Canvas的子项。在附图中,绘制了三条红色折线。黄色矩形是虚构的边界。
var polylines = this.CanvasDraw.Children.Cast<Polyline>();
我想做点什么
double minX;
double minY;
double maxX;
double maxY;
foreach (Polyline polyline in polylines)
{
foreach (var point in polyline.Points)
{
if (point.X is the minimum)
{
minX = point.X;
}
if (point.Y is the minimum)
{
minY = point.Y;
}
if (point.X is the maximum)
{
maxX = point.X;
}
if (point.Y is the maximum)
{
maxY = point.Y;
}
}
}
Point Topleft = new Point(minX, minY);
Point BottomRight = new Point(maxX, maxY);
答案 0 :(得分:1)
您可以使用SelectMany
将所有行中的点数转换为单个集合,然后使用Min()
和Max()
来消除极端情况:
var polylines = this.CanvasDraw.Children.Cast<Polyline>();
// project all points into a single list
var allPoints = polylines.SelectMany(pl=>pl.Points).ToList();
// get mins and maxes
var minX = allPoints.Min(p=>p.X);
var minY = allPoints.Min(p=>p.Y);
var maxX = allPoints.Max(p=>p.X);
var maxY = allPoints.Max(p=>p.Y);
// create bounding points
Point Topleft = new Point(minX, minY);
Point BottomRight = new Point(maxX, maxY);