Search code examples
c#linq-to-sql

LINQ Left Join And Right Join


I need a help,

I have two dataTable called A and B , i need all rows from A and matching row of B

Ex:

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

I need Out Put:

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

Solution

  • 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  |
    

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

    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.