Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq intersect/except with one part of object

Tags:

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?

like image 798
David Archer Avatar asked May 17 '12 09:05

David Archer


Video Answer


1 Answers

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 } 
like image 127
Patryk Ćwiek Avatar answered Sep 25 '22 12:09

Patryk Ćwiek