[英]Select items with a frequency of 1 from a List<T> using LINQ
我有一個Point
類的列表。
列表中的兩個點僅重復一次,其余的重復兩次。
如何使用LINQ找到重復的點?
此解決方案將相同的點分組在一起,從而使您可以僅使用一個成員來查找組,然后返回該成員。
我尚未檢查實際的運行時,但是從性能角度來看,它比解決方案要好得多,該解決方案涉及在Where中運行Count()操作,因為該解決方案可能會在O(n ^ 2)時間運行,而GroupBy實現可能更優雅。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.