intersect two lists with different objects

后端 未结 4 1600
感动是毒
感动是毒 2020-12-09 16:45

I have a list of ObjA and ObjB as follows:

List List1;
List List2;

Both ObjA and ObjB has a common field which is U

4条回答
  •  离开以前
    2020-12-09 17:04

    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));
    

提交回复
热议问题