Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am adiing excel file sheets as datatables in a dataset at runtime. Now i have to join all these data tables based on the conditions present in a list. (List contains column names that the user choose inorder to perform a left join..i.e, select.....on (table1.first item in List==table2.second item in List). I am facing this issue in Windows Form Application using C# and I am using VS2012.
Posted
Updated 22-Dec-14 19:15pm
v2

If you want to join data from different workbooks, the basic idea is here: How to: Get Data from Multiple Workbooks using One OleDbConnection?[^].

You did not provided a way you're fetching data into dataset. If it's a single workbook, you can use OleDbConnection[^] and OleDbCommand[^] to achieve that.
Proper query should looks like:
SQL
SELECT <FieldList>
FROM [Sheet1$] AS t1 INNER JOIN [Sheet2$] AS t2 ON t1.Field1 = t2.Field2

That's all.

[EDIT]
Please, see this: Query Expression Syntax Examples: Join Operators (LINQ to DataSet)[^]

C#
var qry = from x in dtset.Tables(1).AsEnumerable() join y in dtset.Tables(2).AsEnumerable() on x.Field<Type>("Field1") equals y.Field<Type>("Field2")
select new {
    NewField1 = x.Field<Type>(Field1),
    NewField2 = x.Field<Type>(Field2),
    NewField3 = y.Field<Type>(Field1),
    NewField4 = y.Field<Type>(Field2)
    };
foreach(var c in qry)
{
    Console.WriteLine("{0} {1} {2} [3}", c.NewField1, c.NewField2, c.NewField3, c.NewField4);
}
 
Share this answer
 
v2
Comments
arunkx 23-Dec-14 3:07am    
Thank You for the answer. But I am actually comparing woksheets in different workbooks.Now I have the required sheet data in a data table which I add to dataset depnding upon how many sheets the user wants to compare at runtime.(Comparison happens based on Columns of sheets that user chooses). Can linq query help here? If so,please show me how.

Thanks in advance
Maciej Los 23-Dec-14 3:28am    
Actually, i've done it. Please follow the first link.
Yes, Linq can be helpfull.
arunkx 23-Dec-14 3:37am    
I need to join more than two tables. Number of tables to join is unknown as well as the joining condition
Maciej Los 23-Dec-14 4:12am    
See updated answer ;)
I tried linq query and managed to get what I want. Thanks Maciej Los for your time. Here is what I have tried.

DataTable dtab=new DataTable();
dtab = (from a in table1.AsEnumerable()
join b in table2.AsEnumerable()
on a[Field] equals
b[Field] into g
select a).CopyToDataTable();


I placed this in a loop for all the tables in the dataset
 
Share this answer
 

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