【问题标题】:Remove duplicate items from KeyValuePair List by Value按值从 KeyValuePair 列表中删除重复项
【发布时间】:2020-10-10 15:31:50
【问题描述】:

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

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

样本数据:

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)

【问题讨论】:

  • 你有什么尝试吗?
  • 您好 Kunal,我尝试了以下链接,但没有运气。 stackoverflow.com/a/13698224/7300644
  • 这里没有魔法。您需要 (1) 通过 (2) 迭代旧列表来构建新列表,(3) 同时识别重复数据
  • 嗨 Pressacco,我想要一个 Linq 解决方案。我知道迭代是最简单的方法,但想知道它是否可以使用 Linq 解决。
  • 这能回答你的问题吗? Remove duplicate records using LINQ

标签: c# keyvaluepair


【解决方案1】:

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

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

【讨论】:

  • 感谢 Maahi 的回复。
【解决方案2】:

实现 IEqualityComparer&lt;T&gt; 以提供不同的结果,我还重构了您的代码以利用 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)

【讨论】:

  • 感谢库纳尔的努力。
猜你喜欢
  • 2012-11-21
  • 1970-01-01
  • 2014-09-30
  • 2011-01-13
  • 2021-04-02
  • 2016-01-28
相关资源
最近更新 更多