按值从 KeyValuePair 列表中删除重复项

Remove duplicate items from KeyValuePair List by Value

我在 C# 中有一个 KeyValuePair 的列表,格式为 KeyValuePair<long, Point>。 我想从列表中删除具有重复值的项目。

具有 {X,Y} 坐标的 Point 对象。

示例数据:

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

期望输出:

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

您可以在一行中执行此操作:

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

实施 IEqualityComparer<T> 以提供不同的结果,我还重构了您的代码以利用 POCO 实现更好的可维护性 -

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);
        }
    }
}

给出 -

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