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

Determine whether sets are equal (set composed of sets)

我有两个列表 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), 上它应该 return true .

如何使用 Equals 方法?

不使用 linq 检查 foreach 元素的一种方法是 首先创建一个 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();
    }

}

然后使用相等比较器比较两个元素

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

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