一个通用列表,包含积分说=&gt; List<Point>
现在我需要过滤积分并按照以下条件将其存储在另一个List<Point>
中并使用 LINQ 。
•给定值点
•使用最大X 值和最小X 值查找点。
注意:
其实朋友,我正在寻找LINQ查询,如果可能的话,它只在单个查询中执行上述操作。
否则,使用 LINQ ,
进行上述操作的最佳解决方案修改: - 看到我的代码在这里,但我正在寻找排序解决方案.....
int givenY = 147;
List<Point> listOfPointLocal = (from point in listOfPointMain
where point.Y == givenY
select point).ToList();
var minX = listOfPointLocal.Min(p => p.X);
var maxX = listOfPointLocal.Max(p => p.X);
List<Point> listOfFilterdPoint = (from p in listOfPointLocal
where p.X <= minX || p.X >= maxX
select p).ToList();
感谢.....
答案 0 :(得分:2)
在额外课程的帮助下,您只能将列表传递一次。
public class MaxMin
{
public int max { get; set; }
public int min { get; set; }
}
然后
var points = new List<Point>()
{
new Point(10, 10),
new Point(15, 10),
new Point(20, 10),
new Point(42, 42),
new Point(47, 11)
};
var maxmin = new MaxMin() { max = int.MinValue, min = int.MaxValue};
maxmin = points.Where(p => p.Y == 10).
Aggregate(maxmin, (acc, next) =>
{
if (next.X > acc.max) acc.max = next.X;
if (next.X < acc.min) acc.min = next.X;
return acc;
});
答案 1 :(得分:2)
让它有点可读:
var points = new List<Point>()
{
new Point(10, 10),
new Point(15, 10),
new Point(20, 10),
new Point(42, 42),
new Point(47, 11)
};
var maxes = new {
minX = (from p in points orderby p.X select p).First(), // with lowest x
maxX = (from p in points orderby p.X select p).Last(), // with highest x
minY = (from p in points orderby p.Y select p).First(), // with lowest y
maxY = (from p in points orderby p.Y select p).Last() // with highest y
};
答案 2 :(得分:1)
虽然它不能在单个查询中为您提供最小和最大X,但以下代码可能对您有用。
List<Point> list = new List<Point>();
list.Add(new Point(10, 10));
list.Add(new Point(15, 10));
list.Add(new Point(20, 10));
list.Add(new Point(25, 15));
list.Add(new Point(30, 15));
var minX = (from p in list
where (p.Y.Equals(10))
select p.X).Min();
var maxX = (from p in list
where (p.Y.Equals(10))
select p.X).Max();
Console.WriteLine(minX.ToString());
Console.WriteLine(maxX.ToString());
Console.ReadLine();
答案 3 :(得分:1)
这将返回一个结果集,但它仍在迭代列表两次,如果没有AFAIK,你无法做到这一点。
list.Select(a => new
{
Max = list.Where(max => max.Y == ???).Max(max => max.X),
Min = list.Where(min => min.Y == ???).Min(min => min.X)
});