2017-08-08 51 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

相关问题