Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 删除字典中的重复项<;int,List<;点F>&燃气轮机;_C#_Linq - Fatal编程技术网

C# 删除字典中的重复项<;int,List<;点F>&燃气轮机;

C# 删除字典中的重复项<;int,List<;点F>&燃气轮机;,c#,linq,C#,Linq,我有以下代码: 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

我有以下代码:

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) });
但这总是会清空整本字典。我得想办法解决它


谢谢

您可以使用自定义的
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())
    .ToDictionary(g => g.First().Key, g => g.Key);
如果要将其保留为字典,请使用
编辑
,而不是
选择
,然后选择所选的方法来选择键。下面是一个使用
First
的示例(这意味着您将从示例中获得第1项和第3项):


到目前为止,您尝试了什么?您看到了什么结果?一旦你尝试了一些人们乐于帮助的事情,但通常他们希望先看到一些努力。Linq在这里不太合适,它看起来就像代码高尔夫。只需使用嵌套的foreach或实际的设计模式来建模您的行为,而不是使用带有一组列表的字典。您的列表中是否总是有2个
PointF
值?如果是这样的话,看起来您最好使用一个包含此内容的自定义类,而不是创建列表。@DavidG列表中不可能有任何数量的PointF。非常感谢!你能告诉我如何用你的用法示例检索词典吗?我需要原始字典里的钥匙。
var distinctList = dictEntities
    .GroupBy(de => de.Value, new MyComparer())
    .Select(de => de.Key);
var distinctList = dictEntities
    .GroupBy(de => de.Value, new MyComparer())
    .ToDictionary(g => g.First().Key, g => g.Key);