LINQ 左连接和右连接

时间:2023-01-05
本文介绍了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 to SQL:多个列上的多个连接.这可能吗? 下一篇:从 LINQ 到 SQL 获取 SQL 查询?

相关文章

最新文章