Quickest way to find the complement of two collections in C#

前端 未结 3 2040
失恋的感觉
失恋的感觉 2021-01-01 12:02

I have two collections of type ICollection called c1 and c2. I\'d like to find the set of items that are in c2

3条回答
  •  攒了一身酷
    2021-01-01 12:22

    Use Enumerable.Except and specifically the overload that accepts an IEqualityComparer:

    var complement = c2.Except(c1, new MyTypeEqualityComparer());
    

    Note that this produces the set difference and thus duplicates in c2 will only appear in the resulting IEnumerable once. Here you need to implement IEqualityComparer as something like

    class MyTypeEqualityComparer : IEqualityComparer {
        public bool Equals(MyType x, MyType y) {
            return x.Id.Equals(y.Id);
        }
    
        public int GetHashCode(MyType obj) {
            return obj.Id.GetHashCode();
        }
    }
    

提交回复
热议问题