Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get objects which are in both lists based on specific comparator [duplicate]

Tags:

c#

.net

linq

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.

like image 384
James Monger Avatar asked Sep 06 '25 03:09

James Monger


1 Answers

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> {...}
like image 136
Johnny Avatar answered Sep 07 '25 22:09

Johnny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!