C# Linq intersect/except with one part of object

David Archer picture David Archer · May 17, 2012 · Viewed 29.6k times · Source

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?

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · May 17, 2012

Maybe

// returns list of intersecting property 'a' values
foo.Select(f => f.a).Intersect(bar.Select(b => b.a));

BTW property a should be public.