我有一个已排序的对象列表。我想删除冗余对象,其中冗余并不一定意味着重复。这是一个例子:
List<Point> points = new List<Point>
{
new Point(0, 10),
new Point(1, 12),
new Point(2, 16),
new Point(3, 16),
new Point(4, 16),
new Point(5, 13),
new Point(6, 16),
};
我有兴趣删除 new Point(3, 16)
条目,因为它不提供有用的信息;我已经知道2=16处的元素和4=16处的元素。 3=16 的信息对我的应用程序没有任何好处(因为我已经有了边界 {2,4}=16),所以我想删除该条目。我也不想保留第 5 个和第 6 个条目,因为不存在 Y=16 的连续条目。
有没有一种巧妙的方法可以用 linq 来做到这一点?
最佳答案
这个怎么样?
public void Test()
{
List<Point> points = new List<Point>
{
new Point(0, 10),
new Point(1, 12),
new Point(2, 16),
new Point(3, 16),
new Point(4, 16),
new Point(5, 13),
new Point(6, 16),
};
var subSetOfPoints = points.Where(p=> !IsInTheMiddleX(p, points));
}
private bool IsInTheMiddleX(Point point, IEnumerable<Point> points)
{
return points.Any(p => p.X < point.X && p.Y == point.Y) &&
points.Any(p => p.X > point.X && p.Y == point.Y);
}
关于c# - 有没有办法使用 LINQ 从 List<T> 中删除某些元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9969008/