简体   繁体   中英

Select items with a frequency of 1 from a List<T> using LINQ

I have a list of Point classes.

Two of the points are repeated only once in the list and the rest are repeated twice.

How can I find the points that have been repeated once using LINQ?

This solution will group identical points together, allowing you to find the groups with only one member, and return that member.

I haven't checked the actual runtime, but there's a good chance that it's better, performance-wise, than a solution which involves running a Count() operation inside a Where, since that would probably run at O(n^2) time, whereas the GroupBy implementation probably does it more elegantly.

var result = points
 .GroupBy(p => p)
 .Where(group => group.Count() == 1)
 .Select(group => group.First());

尝试这个 :

var result = points.Where(p1 => points.Count(p2 => p1.Contains(p2)) == 1);
using System;
using System.Collections.Generic;
using System.Linq;

class Point
{
    int x, y;
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
    public int X
    {
        get { return x; }
        set { x = value; }
    }
    public int Y
    {
        get { return y; }
        set { y = value; }
    }
}
class Test
{
    static void Main()
    {
        var collection = new List<Point>
        {
            new Point(1,1),
            new Point(1,2),
            new Point(1,1),
            new Point(1,2),
            new Point(3,3),
            new Point(4,5),
        };
        var result = collection.Where(a => collection.Count(b => b.X == a.X && b.Y == a.Y) == 1);
        foreach (var val in result)
            Console.WriteLine(val.X + "," + val.Y);
    }
}
//output:
3,3
4,5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM