Skip to main content
 首页 » 编程设计

c#之判断集合是否相等(集合由集合组成)

2024年02月04日26lhb25

我有两个 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 }, 
                }; 

我想将a 和b 视为集合的集合 所以,在a.Equals(b) 上, 它应该返回 true。

我如何使用 Equals 方法?

请您参考如下方法:

假设您的支票需要无序,您应该检查一下: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; 
}