如何删除列表中的重复对

我得到了一个带有整数对的列表。如果它们是重复的,我如何删除它们?Distinct 不起作用,因为这对可能是 (2, 1) 而不是 (1, 2)。


我的清单是这样的:


1, 2

2, 3

3, 1

3, 2

2, 4

4, 3

...我不需要 (2, 3) 和 (3, 2)


我做了一个public struct FaceLine有public int A和B,然后var faceline = new List<FaceLine>();。


我是 C# 的新手并且迷路了。


不负相思意
浏览 139回答 3
3回答

鸿蒙传说

您可以使用自定义IEqualityComparer<FaceLine>:public class UnorderedFacelineComparer : IEqualityComparer<FaceLine>{&nbsp; &nbsp; public bool Equals(FaceLine x, FaceLine y)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; int x1 = Math.Min(x.A, x.B);&nbsp; &nbsp; &nbsp; &nbsp; int x2 = Math.Max(x.A, x.B);&nbsp; &nbsp; &nbsp; &nbsp; int y1 = Math.Min(y.A, y.B);&nbsp; &nbsp; &nbsp; &nbsp; int y2 = Math.Max(y.A, y.B);&nbsp; &nbsp; &nbsp; &nbsp; return x1 == y1 && x2 == y2;&nbsp; &nbsp; }&nbsp; &nbsp; public int GetHashCode(FaceLine obj)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return obj.A ^ obj.B;&nbsp; &nbsp; }}然后查询非常简单:var comparer = new UnorderedFacelineComparer();List<FaceLine> nonDupList = faceLine&nbsp; &nbsp; .GroupBy(fl => fl, comparer)&nbsp; &nbsp; .Where(g => g.Count() == 1)&nbsp; &nbsp; .Select(g => g.First())&nbsp; &nbsp; .ToList();如果您想保留其中一个重复项,您只需删除Where:List<FaceLine> nonDupList = faceLine&nbsp; &nbsp; .GroupBy(fl => fl, comparer)&nbsp; &nbsp; .Select(g => g.First())&nbsp; &nbsp; .ToList();
打开App,查看更多内容
随时随地看视频慕课网APP