LINQ内部联接 [英] LINQ inner join

查看:68
本文介绍了LINQ内部联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个收藏夹:

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内部联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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