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

前端 未结 3 2043
失恋的感觉
失恋的感觉 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:24

    public class MyTypeComparer : IEqualityComparer
    {
        public MyTypeComparer()
        {    
        }
    
        #region IComparer Members
    
        public bool Equals(MyType x, MyType y)
        {
            return string.Equals(x.Id, y.Id);
        }
    
        public int GetHashCode(MyType obj)
        {
            return base.GetHashCode();
        }
    
        #endregion     
    }
    

    Then, using Linq:

    c3 collection = new collection().add(c1);
    c3.add(c2);
    var items = c3.Distinct(new MyTypeComparer());
    

    You could also do it using generics and predicates. If you need a sample, let me know.

提交回复
热议问题