LINQ Left Join And Right Join(LINQ 左连接和右连接)
问题描述
我需要帮助,
我有两个名为 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.
这篇关于LINQ 左连接和右连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LINQ 左连接和右连接


基础教程推荐
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01
- 创建属性设置器委托 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01