2017-08-08 95 views
1

我有INT確定集是否相等(套組成的集合)

var a = new List<IList<int>>(); 
var b = new List<IList<int>>(); 

他們每個人都具有以下數據列出的兩個列表:

var a = new List<IList<int>>() 
       { 
        new List<int>() { 1, 2 }, 
        new List<int>() { 4, 5, 6 }, 
       }; 

var b = new List<IList<int>>() 
       { 
        new List<int>() { 6, 5, 4 }, 
        new List<int>() { 2, 1 }, 
       }; 

我想看待ab套集所以,在a.Equals(b),它應該返回true。

我該如何做我的Equals方法?

謝謝!這樣做不使用LINQ查詢的foreach元素的

+1

你可以做擴展方法。 – Reniuz

回答

3

假設你的檢查需要比較的兩個元素要命令無知,你應該檢查這個:LINQ : Determine if two sequences contains exactly the same elements

一套套IEqualityComparer實現看起來可能是這樣:

public bool Equals(List<IList<int>> x, List<IList<int>> y) 
{ 
    foreach(var innerList in x) 
    { 
     var innerSet = new HashSet<int>(innerList); 
     var hasEquivalent = false; 

     foreach(var otherInnerList in y) 
     { 
      hasEquivalent = innerSet.SetEquals(otherInnerList); 
      if(hasEquivalent) break; 
     } 

     if(!hasEquivalent) return false; 
    } 

    return true; 
} 
+0

請注意,我沒有比較2個列表,但列出了2個列表,並且我想確定嵌套兩個層次的平等。 – SuperJMN

+0

我已經更新了考慮套集的答案,假設每個內部集合具有相同的固定大小,並且一側的內部集合需要在另一側具有等價物 –

+0

對不起,但對於我的問題,我不能假定每個都有固定的大小。看到我更新的問題(數據)。它應該與樣本中的數據一起工作。 – SuperJMN

1

一種方法是 首先創建一個EqualityComparer

class ListComparer : IEqualityComparer<IList<int>> 
{ 
    public bool Equals(IList<int> x, IList<int> y) 
    { 
     return x.SequenceEqual(y); 
    } 

    public int GetHashCode(IList<int> obj) 
    { 
     throw new NotImplementedException(); 
    } 

} 

然後使用equalitycomparer

var equals= one.SequenceEqual(two,new ListComparer()); 
+0

請注意,我沒有比較2個列表,但列出了2個列表,並且我想要確定兩個嵌套級別的平等。 – SuperJMN

+0

代碼將如下所示,它將比較列表1中的每個元素與列表2,比較listone和listtwo時,它將使用ListCompare與intern對待listone和listtwo的元素作爲列表,並將它們與列表進行比較,代碼也可以修改,以便通過更改公共bool等於(IList x,IList y) { return x .SequenceEqual(y,new ListComparer()); } – user5195490

相關問題