LINQ 左连接和右连接
- 作者: 今后丶何如
- 来源: 51数据库
- 2022-12-08
问题描述
我需要帮助,
我有两个名为 A 和 B 的数据表,我需要 A 中的所有行和 B 的匹配行
I have two dataTable called A and B , i need all rows from A and matching row of B
例如:
A: B: User | age| Data ID | age|Growth 1 |2 |43.5 1 |2 |46.5 2 |3 |44.5 1 |5 |49.5 3 |4 |45.6 1 |6 |48.5
我需要输出:
User | age| Data |Growth ------------------------ 1 |2 |43.5 |46.5 2 |3 |44.5 | 3 |4 |45.6 |
推荐答案
您提供的示例数据和输出并未演示左连接.如果是左连接,您的输出将如下所示(注意我们如何为用户 1 提供 3 个结果,即用户 1 拥有的每个增长记录一次):
The example data and output you've provided does not demonstrate a left join. If it was a left join your output would look like this (notice how we have 3 results for user 1, i.e. once for each Growth record that user 1 has):
User | age| Data |Growth ------------------------ 1 |2 |43.5 |46.5 1 |2 |43.5 |49.5 1 |2 |43.5 |48.5 2 |3 |44.5 | 3 |4 |45.6 |
假设你仍然需要一个左连接;以下是在 Linq 中执行左连接的方法:
Assuming that you still require a left join; here's how you do a left join in Linq:
var results = from data in userData
join growth in userGrowth
on data.User equals growth.User into joined
from j in joined.DefaultIfEmpty()
select new
{
UserData = data,
UserGrowth = j
};
如果您想进行正确的连接,只需交换您从中选择的表,如下所示:
If you want to do a right join, just swap the tables that you're selecting from over, like so:
var results = from growth in userGrowth
join data in userData
on growth.User equals data.User into joined
from j in joined.DefaultIfEmpty()
select new
{
UserData = j,
UserGrowth = growth
};
代码的重要部分是 into 语句,然后是 DefaultIfEmpty.这告诉 Linq,如果另一个表中没有匹配的结果,我们希望使用默认值(即 null).
The important part of the code is the into statement, followed by the DefaultIfEmpty. This tells Linq that we want to have the default value (i.e. null) if there isn't a matching result in the other table.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
