如何使用LINQ查找列表中只重复一次的项

本文关键字:一次 LINQ 何使用 查找 列表 | 更新日期: 2023-09-27 18:09:44

假设我们有一个List<Point> Points,如下所示,我如何获得Point对象在列表中只重复一次:p(30,10)和p (30,0)

var Points = new List<Point>
{
    new Point { X = 0, Y = 0 },
    new Point { X = 10, Y = 20 },
    new Point { X = 30, Y = 10 },
    new Point { X = 30, Y = 0 },
    new Point { X = 0, Y = 0 },
    new Point { X = 10, Y = 20 }
};
public class Point
{
    public double X;
    public double Y;
};

如何使用LINQ查找列表中只重复一次的项

var query = Points
    .GroupBy(p => new { p.X, p.Y }) // Group points based on (X,Y).
    .Where(g => g.Count() == 1)     // Take groups with exactly one point.
    .Select(g => g.Single());       // Select the point in each group.