LINQ左联接和右联接 [英] LINQ Left Join And Right Join
问题描述
我需要帮助
我有两个名为A和B的dataTable,我需要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左联接和右联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!