将两个列表与不同的对象相交

时间:2012-07-01 19:36:26

标签: c# linq

我有一个ObjA和ObjB列表如下:

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

ObjA和ObjB都有一个共同的字段,即User,我想根据User.Id与它们相交。

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

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

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

如何将这两个列表与Linq上的User.Id相交?

因此,我只想要用户列表。

4 个答案:

答案 0 :(得分:32)

一般的想法是

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

但是,本身假设User实现IEquatable<User>,这似乎不是这种情况。因此,您需要添加此实现或使用接受自定义IEqualityComparer<User>Intersect重载。

答案 1 :(得分:7)

不需要IEqualityComparer或IEquatable(无论如何都会更好)

var commonUsers = list1
                  .Select(l1 => l1.User)
                  .Where(u => list1
                       .Select(l => l.User.Id)
                       .Intersect(list2
                          .Select(l2 => l2.Id))
                       .Contains(u.Id));

var commonUsers = list1.Select(l1 => l1.User)
                      .Where(u=> list2.Select(l2 => l2.User.Id)
                                        .Contains(u.Id));

答案 2 :(得分:3)

1.看看这个简单的代码

  var result = (from objA in objAList
                join objB in objBList on objA.user.Id equals objB.user.Id
                select objA/*or objB*/).ToList();

2.完整代码

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

答案 3 :(得分:2)

标准方法是使用IEqualityComparer对象。默认值使用标准相等比较。创建一个实现IEqualityComparer接口的类,并执行所需的比较。然后,您可以调用IEnumerable.Intersect的重载,该重载接受自定义比较类的实例