Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have two collections of type ICollection<MyType> called c1 and c2. I'd like to find the set of items that are in c2 that are not in c1, where the heuristic for equality is the Id property on MyType.

What is the quickest way to perform this in C# (3.0)?

like image 968
Ben Aston Avatar asked Feb 03 '10 17:02

Ben Aston


1 Answers

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

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<MyType> once. Here you need to implement IEqualityComparer<MyType> as something like

class MyTypeEqualityComparer : IEqualityComparer<MyType> {     public bool Equals(MyType x, MyType y) {         return x.Id.Equals(y.Id);     }      public int GetHashCode(MyType obj) {         return obj.Id.GetHashCode();     } } 
like image 128
jason Avatar answered Sep 19 '22 22:09

jason