2012-03-28 34 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); 

是否有(默認值?)比較器我可以插入HashSet,以便s1.Equals(s2)是真的? 我知道有一個StructuralComparisons.StructuralEqualityComparer,但HashSet需要一個通用的IEqualityComparer> <>。c#結構比較int列陣的哈希集

UPDATE:

看起來不像它都不能正常工作。我得到的最接近的是使用HashSet.SetEquals並插上了StructuralComparisons.StructuralEqualityComparer的包裝由phoog的建議

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 2012-03-28 15:54:23

+1

'Enumerable.SequenceEqual'會爲你做這份工作嗎?不知道是否會出現訂購問題...可能.. – Servy 2012-03-28 15:56:16

+1

您可以在委託給StructuralComparisons.StructuralEqualityComparer的包裝類上實現'IEqualityComparer''。 – phoog 2012-03-28 16:02:20

回答

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); 
    } 
}