DarthVader DarthVader - 1 month ago 9
C# Question

intersect two lists with different objects

I have a list of ObjA and ObjB as follows:

List<ObjA> List1;
List<ObjB> List2;


Both ObjA and ObjB has a common field which is User and I want to intersect them based on User.Id.

class ObjA
{
User user;
.... other properties
}

class ObjB
{
User user;
.... other properties
}

class User
{
int Id;
.... other props
}


How can i intersect these two lists on User.Id with linq?

As a result I want only the list of Users.

Jon Jon
Answer

The general idea is

var commonUsers = list1.Select(a => a.User).Intersect(list2.Select(b => b.User));

However, by itself this assumes that User implements IEquatable<User>, which does not seem to be the case here. So you either need to add this implementation or use the Intersect overload that accepts a custom IEqualityComparer<User>.

Comments