I've got a class:
class ThisClass { private string a {get; set;} private string b {get; set;} }
I would like to use the Intersect and Except methods of Linq, i.e.:
private List<ThisClass> foo = new List<ThisClass>(); private List<ThisClass> bar = new List<ThisClass>();
Then I fill the two lists separately. I'd like to do, for example (and I know this isn't right, just pseudo code), the following:
foo[a].Intersect(bar[a]);
How would I do this?
If you want a list of a single property you'd like to intersect then all the other pretty LINQ solutions work just fine. BUT! If you'd like to intersect on a whole class though and as a result have a List<ThisClass>
instead of List<string>
you'll have to write your own equality comparer.
foo.Intersect(bar, new YourEqualityComparer());
same with Except
.
public class YourEqualityComparer: IEqualityComparer<ThisClass> { #region IEqualityComparer<ThisClass> Members public bool Equals(ThisClass x, ThisClass y) { //no null check here, you might want to do that, or correct that to compare just one part of your object return x.a == y.a && x.b == y.b; } public int GetHashCode(ThisClass obj) { unchecked { var hash = 17; //same here, if you only want to get a hashcode on a, remove the line with b hash = hash * 23 + obj.a.GetHashCode(); hash = hash * 23 + obj.b.GetHashCode(); return hash; } } #endregion }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With