Remove duplicate items from KeyValuePair List by Value

962 Views Asked by At

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)
2

There are 2 best solutions below

1
On BEST ANSWER

You can do this in single line:

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

1
On

Implement the IEqualityComparer<T> to give distinct results, also I refactored your code to make a use of POCO for better maintainability -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;

namespace TestApp
{
    public class PointKVP
    {
        public long Id { get; set; }
        public Point Point { get; set; }

        public override string ToString()
        {
            return $"{Id},({Point.X}, {Point.Y})";
        }
    }

    public class PointKVPEqualityComparer : IEqualityComparer<PointKVP>
    {
        public bool Equals(PointKVP x, PointKVP y)
        {
            if (x.Point.X == y.Point.X && x.Point.Y == y.Point.Y)
            {
                return true;
            }
            else if (x.Point == default(Point) && y.Point == default(Point))
            {
                return true;
            }
            else if (x.Point == default(Point) || y.Point == default(Point))
            {
                return false;
            }
            else
            {
                return false;
            }
        }

        public int GetHashCode(PointKVP obj)
        {
            return (int)obj.Point.X ^ obj.Point.Y;
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            List<PointKVP> Data = new List<PointKVP>
             {
                new PointKVP
                {
                    Id = 1,
                    Point = new Point(10,10)
                },
                new PointKVP
                {
                    Id = 2,
                    Point = new Point(10,10)
                },
                new PointKVP
                {
                    Id = 3,
                    Point = new Point(10,15)
                }
             };

            Data.Distinct(new PointKVPEqualityComparer()).ToList().ForEach(Console.WriteLine);
        }
    }
}

Which gives -

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