linq-to-sql – LINQ Left Join And Right Join

前端之家收集整理的这篇文章主要介绍了linq-to-sql – LINQ Left Join And Right Join前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要一个帮助,

我有两个dataTable称为A和B,我需要所有行从A和匹配行的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

我需要Out Put:

User | age| Data |Growth
------------------------                           
1    |2   |43.5  |46.5                           
2    |3   |44.5  |                          
3    |4   |45.6  |

解决方法

您提供的示例数据和输出显示左连接.如果是左连接,您的输出将如下所示(注意我们如何为用户1获得3个结果,即用户1拥有的每个成长记录一次):
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中进行左加盟的方式:

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
              };

如果你想做一个正确的连接,只需将你所选择的表互换,就像这样:

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).

猜你在找的MsSQL相关文章