2012-03-28 3 views
2
var comparer = ... 
var s1 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } }, comparer); 
var s2 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } }, comparer); 

(기본값?) 비교 자 s1.Equals (s2)가 참이되도록 HashSet에 연결할 수 있습니까? StructuralComparisons.StructuralEqualityComparer가 있지만 HashSet에는 일반 IEqualityComparer <>이 필요합니다.int 배열의 해시 집합에 대한 구조적 비교

UPDATE : 이제까지 일할 수있는 것처럼

가 보이지 않습니다. phoog에 의해 제안 내가 할 가장 가까운 HashSet.SetEquals를 사용하고 StructuralComparisons.StructuralEqualityComparer의 래퍼를 연결하는 것입니다

internal class GenericStructuralComparer<T> : IEqualityComparer<T> 
    { 
     static GenericStructuralComparer<T> _instance; 

     public static IEqualityComparer<T> Instance 
     { 
      get { return _instance ?? (_instance = new GenericStructuralComparer<T>()); } 
     } 

     public bool Equals(T x, T y) 
     { 
      return StructuralComparisons.StructuralEqualityComparer.Equals(x, y); 
     } 

     public int GetHashCode(T obj) 
     { 
      return StructuralComparisons.StructuralEqualityComparer.GetHashCode(obj); 
     } 
    } 

    public static IEqualityComparer<T> StructuralComparer<T>() 
    { 
     return GenericStructuralComparer<T>.Instance; 
    } 

그리고

var comparer = StructuralComparer<int[]>(); 
var s1 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } }, comparer); 
var s2 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } }, comparer); 
s1.SetEquals(s2); // True 
+0

내가 모르는 무슨을 하나의 내장하지만 하나를 구현하기가 상대적으로 쉽다. 내가 보는 가장 큰 문제점은'GetHashCode()'가'O (n)'이 될 것이라는 것입니다. – CodesInChaos

+1

'Enumerable.SequenceEqual'이 당신을 대신 할 것입니까? 주문 문제가 있을지 모르겠다. 아마도 .. – Servy

+1

'StructuralComparisons.StructuralEqualityComparer'에 위임하는 래퍼 클래스에'IEqualityComparer '을 구현할 수 있습니다. – phoog

답변

2

없음 - 암시 적 배열 평등 참조 이상으로 정의되어 있지 않기 때문에 품질; 런타임시 배열은 내부 요소를 고려하는 GetHashCode을 제공하지 않습니다. 왜냐하면 해시 코드를 결합하는 일반적인 경우가 없으므로 프레임 워크가이를 구현하려고하지 않기 때문입니다.

자신 만의 롤을 만들어야합니다.

0

아니, 기본이 더 비교 자 없다하지만 트릭을 수행 이와 같은 확장자 방법을 만들 수 있습니다

public static class HashSetExt 
{ 
    public static bool HashSetEqualsTo<T>(this HashSet<T> set, HashSet<T> other) 
    { 
     return //Your own compare method 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var s1 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } }); 
     var s2 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } }); 
     var isEquals = s1.HashSetEqualsTo<int[]>(s2); 
    } 
}