相交不同的对象两份名单 [英] intersect two lists with different objects

查看:133
本文介绍了相交不同的对象两份名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有ObjA和ObjB名单如下:

 列表< ObjA> List1中; 
名单,LT; ObjB>列表2;



无论ObjA和ObjB有一个共同的领域,这是用户,我想根据用户交叉他们。 (出处同上)

 类ObjA 
{
的用户的用户;
....其他属性
}

类ObjB
{
的用户的用户;
....其他属性
}

类用户
{
INT标识;
....等道具
}



我怎样才能相交这两个使用LINQ的User.Id名单?



因此,我只希望用户列表。


< DIV CLASS =h2_lin>解决方案

的总体思路是

  VAR commonUsers = list1.Select (一个= GT; a.User).Intersect(list2.Select(二= GT; b.User)); 



不过,本身这个假定用户工具 IEquatable<使用者> ,这似乎并没有在这里如此。所以,你要么需要添加此实现或使用接受一个自定义的相交超载/ ms132151> 的IEqualityComparer<使用者方式>


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>.

这篇关于相交不同的对象两份名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆