2

Let T1 and T2 are DataTables with following fields

T1(CustID, ColX, ColY)

T2(CustID, ColZ)

I need to perform Left join on CustID

How this can be done in C# code in a simple way?

Thanks.

Indrajit
  • 51
  • 3
  • 9
  • 2
    same question ? i dont understand why you post it again here is the link http://stackoverflow.com/questions/665754/inner-join-in-datatable-in-c-sharp – rahularyansharma Jan 29 '12 at 17:39
  • Your question is not clear. Joining tables is about SQL, not about C#. Databases can be accessed in many ways. Here is just one [Retrieving Data Using a DataReader](http://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.90).aspx) described on MSDN. – Olivier Jacot-Descombes Jan 29 '12 at 17:49
  • The OP is asking about left join. The link @rahularyansharma posted was for an inner join. – Jeremy Armstrong Jan 29 '12 at 17:53

3 Answers3

2

You can use LINQ to do this. Here is the pseudocode for a left join on two data collections:

T1.rows.Select(leftRow=>new{
CustID = leftRow.CustID
ColX = leftRow.ColX
ColY = leftRow.ColY
ColZ = T2.Select(rightRow=>rightRow.ColZ).Where(rightRow=>rightRow.CustID == leftRow.CustID).FirstOrDefault()
});
Jeremy Armstrong
  • 885
  • 9
  • 22
0

Use below query for the left outer join

 var query = from t_1 in T1 
                        join t_2 in T2 on t_1.CustID equals t2.CustID into gj
                        from subpet in gj.DefaultIfEmpty()
                        select new { x= t_1.ColX,y=t_2.ColY};
bummi
  • 27,123
  • 14
  • 62
  • 101
user1089766
  • 597
  • 6
  • 14
0

It seems as though you might be driving at the .NET concept of Linq. If that's the case, this question talks about Left Join using Linq.

If not, just think about what a left join is and create a type that matches what you want (CustID, ColX, ColY, ColZ) where ColZ is nullable and populate it according to rules of left join.

Community
  • 1
  • 1
Erik Dietrich
  • 6,080
  • 6
  • 26
  • 37