gpt4 book ai didi

c# - 将两个具有不同对象的列表相交

转载 作者:行者123 更新时间:2023-12-03 13:16:41 25 4
gpt4 key购买 nike

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

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

ObjA 和 ObjB 都有一个公共(public)字段,即用户,我想根据 User.Id 将它们相交。
class ObjA
{
User user;
.... other properties
}

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

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

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

结果,我只想要用户列表。

最佳答案

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

关于c# - 将两个具有不同对象的列表相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11285045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com