I have two List
objects, listA
and listB
, which contain a collection of User
objects.
Each User
object has a property ID
.
I want to get a list of users which are present in both listA
and listB
based on their ID
property.
Here is my code so far:
listA.Where(a => listB.Any(b => b.ID == a.ID));
Is there a better way to do this? It feels like it could be inefficient, especially if listB
is large.
The User
object does not implement IEquatable
.
If User
implements IEquatable<User>
, assumption is that two User
are the same if ID
are the same, then you can use LINQ Intersect
. For example:
listA.Intersect(listB);
If User
does not implement IEquatable<User>
you can invoke Intersect
with IEqualityComparer<User>
. For Example:
listA.Intersect(listB, new UserEqualityComparer());
where
UserEqualityComparer : IEquatable<User> {...}
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