简体   繁体   English

从数据点列表中取出不同的项目

[英]Taking distinct item from list of datapoints

I have a list of Datapoints (List). 我有一个数据点列表(列表)。

e.g

original list
(1,2)
(2,2)
(1,3)
(3,3)
(4,3)
(2,3)
(5,4)

I want a output list as

(1,2)
(2,2)
(3,3)
(4,3)
(5,4)
or

(1,3)
(3,3)
(4,3)
(2,3)
(5,4)

ie I want to remove all the other points where X value duplicates. 即我想删除X值重复的所有其他点。

One approach that I have is to loop through all the point and take the current point x value and compare it with rest of the list if it equals other points X value then remove that value. 我要采用的一种方法是遍历所有点并获取当前点x值,如果与其他点X值相等,则将其与列表的其余部分进行比较,然后删除该值。

How will I do that using LINQ or some extension method(Distinct) 我将如何使用LINQ或某些扩展方法(独特)

One approach with LINQ would be to group points by their X-coordinates, and then pick some arbitrary item from each group to produce the output. LINQ的一种方法是将点按其X坐标分组,然后从每个组中选择一些任意项以产生输出。

var filtered = myList.GroupBy(point => point.XValue) // point's bucket depends on its X
                     .Select(group => group.First()) //pick first item from each bucket
                     .ToList();

EDIT: A simple way of doing it without LINQ: 编辑:一种无需LINQ的简单方法:

var pointsByXCoord = new Dictionary<double, DataPoint>();

foreach(var point in myList)
   pointsByXCoord[point.XValue] = point;

var filtered = pointsByXCoord.Values;

var enumerable = myList.Distinct() will return an IEnumerable<Datapoint> as long as the Datapoint has implemented the IEquatable<> interface. 只要Datapoint已实现IEquatable<>接口, var enumerable = myList.Distinct()就会返回IEnumerable<Datapoint>

Here is a nice article on the requirements for the custom type in order to be able to use Distinct() extension from LINQ: 这是一篇关于自定义类型的要求的不错的文章,以便能够使用LINQ的Distinct()扩展:

http://blogs.msdn.com/b/csharpfaq/archive/2009/03/25/how-to-use-linq-methods-to-compare-objects-of-custom-types.aspx http://blogs.msdn.com/b/csharpfaq/archive/2009/03/25/how-to-use-linq-methods-to-compare-objects-of-custom-types.aspx

If you need a list instead of an IEnumerable a ToList() extension is also provided. 如果您需要列表而不是IEnumerable则还提供ToList()扩展。

I think it's better solution: 我认为这是更好的解决方案:

var filtered =
myList.GroupBy(point =>
point.XValue.ToString() + "," point.YValue[0].ToString()).Select(group => group.First
()).ToList();

because with only xvalue datapoint is not unique. 因为只有xvalue数据点不是唯一的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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