Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intersect two different IEnumerable collections

i think this question has been asked before but i havent been able to deduce a clear answer. I am trying to find the best way (or a way) to intersect two completely different ienumerable collections.

class A:

  • int z1
  • int z2
  • int z3
  • string z4

class B:

  • int j5
  • int j6
  • T j7
  • T j8
  • string j9

..I want to intersect List<A> with List<B> on z2 == j6.

can this be done?

like image 680
Grant Avatar asked Mar 29 '11 06:03

Grant


Video Answer


2 Answers

The question doesn't really make sense - what would the result type be? Intersections have to be performed on two sequences of the same type. It sounds like you don't so much want an intersection between two sets, as a filter of the first sequence based on possible values of z2. For example:

HashSet<int> validZ2 = new HashSet<int>(listB.Select(x => x.j6));
var filtered = listA.Where(x => validZ2.Contains(x.z2));

Or possibly as Gabe suggests, you want a join. For example:

var query = from a in listA
            join b in listB on a.z2 equals b.j6
            select new { a, b };

That will give you all pairings of values from the two lists which match on z2/j6.

like image 194
Jon Skeet Avatar answered Nov 11 '22 11:11

Jon Skeet


You need to implement a custom equality comparer (see IEqualityComparer<T> interface) to pass it as a second argument to Intersect().

like image 35
UserControl Avatar answered Nov 11 '22 12:11

UserControl