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

时间:2014-06-23 04:45:06

标签: c# linq list

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

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;
};

1 个答案:

答案 0 :(得分:4)

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.
相关问题