我有两个收藏夹:
List<int> ids; List<User> users;User具有ID,名称等的地方.
我想内部加入这两个集合,并返回一个新的List<int>,其ID来自第一个集合,该ID也位于第二个集合(用户ID)中.
我是LINQ的新手,也不知道从哪里开始.
谢谢.
解决方案您无需使用join即可:
List<int> commonIds = ids.Intersect(users.Select(u => u.Id)).ToList();针对评论中的问题,您无需使用Join即可获得用户列表:
var matchingUsers = users.Where(u => ids.Contains(u.Id));但是,这非常低效,因为Where子句必须扫描每个用户的ID列表.我认为Join是处理这种情况的最佳方法:
List<User> matchingUsers = users.Join(ids, u => u.Id, id => id, (user, id) => user).ToList();I have two collections:
List<int> ids; List<User> users;Where User has id, name, etc.
I would like to inner join these two collections and return a new List<int> with ids from the first collection which are also in the second collection (User id's).
I am new to LINQ and don't know where to start.
Thanks.
解决方案You don't need to use join to do this:
List<int> commonIds = ids.Intersect(users.Select(u => u.Id)).ToList();EDIT: In response to the question in the comments, you could get a list of users without using Join:
var matchingUsers = users.Where(u => ids.Contains(u.Id));However this is quite inefficient since the Where clause has to scan the list of ids for each user. I think Join would be the best way to handle this case:
List<User> matchingUsers = users.Join(ids, u => u.Id, id => id, (user, id) => user).ToList();
更多推荐
LINQ内部联接
发布评论