如何解决按值从KeyValuePair列表中删除重复项
我有一个keyvaluePair
的C#列表,格式为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,Point>(3,15)));
所需的输出:
1,(10,10)
3,15)
解决方法
您可以单行执行此操作:
var结果= 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,new PointKVP
{
Id = 3,15)
}
};
Data.Distinct(new PointKVPEqualityComparer()).ToList().ForEach(Console.WriteLine);
}
}
}
哪个给--
1,(10,10)
3,15)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。