LINQ内部联接

编程入门 行业动态 更新时间:2024-10-27 06:29:11
本文介绍了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内部联接

本文发布于:2023-10-15 00:43:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!