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.
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>
.
1.look at this simple code
var result = (from objA in objAList
join objB in objBList on objA.user.Id equals objB.user.Id
select objA/*or objB*/).ToList();
2.complete code
class QueryJoin
{
static void Main(string[] args)
{
//create users
User user1 = new User { Id = 1, Name = "anuo1" };
User user2 = new User { Id = 2, Name = "anuo2" };
User user3 = new User { Id = 3, Name = "anuo3" };
User user4 = new User { Id = 4, Name = "anuo4" };
User user5 = new User { Id = 5, Name = "anuo5" };
//create objAList
List<ObjA> objAList = new List<ObjA>();
objAList.Add(new ObjA { user = user1 });
objAList.Add(new ObjA { user = user2 });
objAList.Add(new ObjA { user = user3 });
//create objBList
List<ObjB> objBList = new List<ObjB>();
objBList.Add(new ObjB { user = user3 });
objBList.Add(new ObjB { user = user4 });
objBList.Add(new ObjB { user = user5 });
//intersect
var result = (from objA in objAList
join objB in objBList on objA.user.Id equals objB.user.Id
select objA/*or objB*/).ToList();
}
}
class ObjA
{
public User user { get; set; }
}
class ObjB
{
public User user { get; set; }
}
class User
{
public int Id { get; set; }
public string Name { get; set; }
}
without need of IEqualityComparer or IEquatable (which would be better anyway)
var commonUsers = list1
.Select(l1 => l1.User)
.Where(u => list1
.Select(l => l.User.Id)
.Intersect(list2
.Select(l2 => l2.Id))
.Contains(u.Id));
or
var commonUsers = list1.Select(l1 => l1.User)
.Where(u=> list2.Select(l2 => l2.User.Id)
.Contains(u.Id));
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