Search code examples
c#keyvaluepair

Remove duplicate items from KeyValuePair List by Value


I have a List of KeyValuePair in C# formatted as KeyValuePair<long, Point>. I want to remove items having duplicate values from List.

The Point object having {X,Y} coordinates.

Sample Data:

List<KeyValuePair<long, Point>> Data= new List<KeyValuePair<long,Point>>();
Data.Add(new KeyValuePair<long,Point>(1,new Point(10,10)));
Data.Add(new KeyValuePair<long,Point>(2,new Point(10,10)));
Data.Add(new KeyValuePair<long,Point>(3,new Point(10,15)));

Desired Output:

1,(10,10)    
3,(10,15)

Solution

  • You can do this in single line:

    var result = Data.GroupBy(x => x.Value).Select(y => y.First()).ToList();