我有以下代码:
Dictionary<int, List<PointF>> dictEntities = new Dictionary<int, List<PointF>>();
dictEntities.Add(1, new List<PointF>() { new PointF(1.0F, 2.0F), new PointF(3.0F, 4.0F) });
dictEntities.Add(2, new List<PointF>() { new PointF(3.0F, 4.0F), new PointF(1.0F, 2.0F) });
dictEntities.Add(3, new List<PointF>() { new PointF(7.0F, 8.0F), new PointF(9.0F, 6.0F) });
我想删除列表中重复的字典条目。 删除重复项后的预期结果:字典现在包含2个条目(“1”和“3”或“2”和“3”),因为条目1和2具有相同的PointF列表。从字典中删除1或2。我想我必须首先对List进行排序,然后以某种方式对其进行区分?但是我如何删除重复的条目呢?
到目前为止我所尝试的是:
foreach (var item in dictEntities.ToList())
{
while (dictEntities.Values.Contains(item.Value))
{
dictEntities.Remove(item.Key);
}
}
但这总是清空整本字典。我必须以某种方式解决它。
谢谢
答案 0 :(得分:2)
您可以使用自定义IEqualityComparer
并使用GroupBy
执行此操作。例如:
public class MyComparer : IEqualityComparer<List<PointF>>
{
public bool Equals(List<PointF> l1, List<PointF> l2)
{
//If lists contain different amount of items, they are different
if(l1.Count() != l2.Count()) return false;
//Order the lists by X then Y, that way we can compare them in order
var orderedL1 = l1.OrderBy(p => p.X).ThenBy(p => p.Y).ToList();
var orderedL2 = l2.OrderBy(p => p.X).ThenBy(p => p.Y).ToList();
for(var i = 0; i < l1.Count(); i++)
{
if(orderedL1[i].X != orderedL2[i].X) return false;
if(orderedL1[i].Y != orderedL2[i].Y) return false;
}
//They must be the same if we reached here
return true;
}
public int GetHashCode(List<PointF> dp)
{
return 0;
}
}
并像这样使用它:
var distinctList = dictEntities
.GroupBy(de => de.Value, new MyComparer())
.Select(de => de.Key);
如果您想将其保留为字典而不是Select
,请使用ToDictionary
并选择方法来选择密钥。以下是使用First
的示例(这意味着您将从示例中获得第1项和第3项):
var distinctList = dictEntities
.GroupBy(de => de.Value, new MyComparer())
.ToDictionary(g => g.First().Key, g => g.Key);