list - Intersect between 2 collections in C# -
i have:
list<infraestructura> l1 = listq1.tolist(); list<infraestructura> l2 = listq2.tolist();
and need intersect comparing ids. that:
l1.intersect(l2, l1[].id_infraestructura == l2[].id_infraestructura)
but don't know method must use , sintax.
i found this:
var ids = list1.select(a => a.id).intersect(list2.select(b => b.id));
but return list of ids , need list of elements contained in both lists.
thank you!
the other answers correct, can use intersect
custom comparer. can create custom comparer implementing iequalitycomparer<>
interface. , implementing interface must implmenet 2 methods, equals
, gethashcode
.
public class infraestructuracomparer: iequalitycomparer<infraestructura> { /// <summary> /// whether 2 infraestructura equal. /// </summary> public bool equals(infraestructura firstobj, infraestructura secondobj) { if (firstobj == null && secondobj == null) return true; if (firstobj == null || secondobj == null) return false; // equality logic goes here return firstobj.id == secondobj.id; } /// <summary> /// return hash code instance. /// </summary> public int gethashcode(infraestructura obj) { // don't compute hash code on null object. if (obj == null) return 0; unchecked { var hash = 17; hash = hash * 23 + obj.id.gethashcode(); return hash; } } }
and then:
var result = list1.intersect(list2, new infraestructuracomparer());
you can use comparer in except
method, finding difference of 2 sequences.
var result = list1.except(list2, new infraestructuracomparer());
additionally:
from first point of view may misunderstood gethashcode()
. can read method in many question of stackoverflow. can read answer question.
Comments
Post a Comment