Click here to Skip to main content
14,695,590 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have two DataTables like

DataTable1-
IDPart1    IDPart2    Type
1AType1
1AType2


DataTable2-
IDPart1    IDPart2    Range
1A100
1A200
1A300


Now I need my main datatable to be :-
IDPart1    IDPart2    Range   Type
1A100Type1
1A200Type2
1A300


Here IDPart1 and IDPart2 are common columns for both datatable. Now for ID 1-A, i have 2 records in DataTable1 and 3 records in DataTable2.
I want my DataTable to have 3 records with type column from DataTable1 to have an empty string due to lesser records in DataTable1.

Note: There might be a case when I have lesser records in DataTable2 and more records in DataTable1 for a ID combination.

Is there any way in LINQ or any other way to achieve this.
Posted
Comments
Kornfeld Eliyahu Peter 18-Nov-14 5:19am
   
What connect Type1 to 1-A-100 and not to 1-A-300?
Member 11242821 18-Nov-14 8:01am
   
There is nothing which connects Type and Range columns. They are totally independent of each other.
If I use a left join on IDPart1 and IDPart2 between two datatables, it results in a kind of cross join i.e. gives me every type of DataTable1 with every range of DataTable2.

1 solution

Hi,

Please try this.
List<table1> lstt1 = new List<table1>();
lstt1.Add(new Table1() { IDPart1 = "1A", Type = "T1" });
lstt1.Add(new Table1() { IDPart1 = "1A", Type = "T2" });

List<table2> lstt2 = new List<table2>();
lstt2.Add(new Table2() { IDPart1 = "1A", Range = 100 });
lstt2.Add(new Table2() { IDPart1 = "1A", Range = 200 });
lstt2.Add(new Table2() { IDPart1 = "1A", Range = 300 });

 var items = from itm1 in lstt1
             join itm2 in lstt2 on itm1.IDPart1 equals itm2.IDPart1
             into grouping
             from itm2 in grouping.DefaultIfEmpty(new Table2())
             select new { itm1.IDPart1, itm1.Type, itm2.Range };
   
v2
Comments
Member 11242821 18-Nov-14 6:53am
   
What is Table2() here?
X Vinoth Arun Raj 25-Nov-14 2:06am
   
table2() is class or entity

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900