我需要帮助
我有两个名为A和B的dataTable,我需要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
我需要输出:
User | age| Data |Growth ------------------------ 1 |2 |43.5 |46.5 2 |3 |44.5 | 3 |4 |45.6 |
您提供的示例数据和输出未演示左连接。如果是左联接,您的输出将如下所示(注意,我们如何为用户1获得3个结果,即对于用户1的每个Growth记录一次)
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 };
该代码的重要部分是in语句,后跟DefaultIfEmpty。这告诉Linq如果另一个表中没有匹配的结果,我们希望具有默认值(即null)。