strong textThanks to Tim who provided me the code below in this other post: Join/merge two excel files in asp.net and display them in gridview.
My question in this new post is:
How can I reuse or add linq result to a dataset or datatabe so that I can query the new table and not the two separate tables? The join keyword gave me the possibility to join the two tables. Now I would like to use this joined table to run other queries on it.
I hope my question makes sense. If you need more info, please let me know.
DataSet ds = new DataSet("Stock");
using (var dbConnection = new OleDbConnection(connString))
using (var dbCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", dbConnection))
using (var da = new OleDbDataAdapter(dbCommand))
{
da.Fill(ds, "HWTypes");
}
using (var dbConnection = new OleDbConnection(stockConn))
using (var dbCommand = new OleDbCommand("SELECT * FROM [Stock_voorlopig$]", dbConnection))
using (var da = new OleDbDataAdapter(dbCommand))
{
da.Fill(ds, "Stock");
}
var joined = from rType in ds.Tables["HWTypes"].AsEnumerable()
join rStock in ds.Tables["Stock"].AsEnumerable()
on rType.Field<string>("ProductID") equals rStock.Field<string>("Partno")
select new
{
ProductID = rType.Field<string>("ProductID")
// add the other columns you need here
};
GridView1.DataSource = joined;
GridView1.DataBind();
Edit 1:
I am trying to do something like this:
private static DataTable JoinDataTablesWithLinq()
{
//rest of the code from above
return joined.CopyToDataTable();
}
But I am getting this error:
The type 'AnonymousType#1' cannot be used as type parameter 'T' in the generic type or method 'System.Data.DataTableExtensions.CopyToDataTable<T>(System.Collections.Generic.IEnumerable<T>)'. There is no implicit reference conversion from 'AnonymousType#1' to 'System.Data.DataRow'.
Any help?
You cannot create a
DataTable“on the fly”. You have selected an anonymous type which is not aIEnumerable<DataRow>which you need to useCopyToDataTable. So you either have to use a custom class and fill aList<MyClass>with all properties you need to persist it or you have to create aDataTablewith all necessaryDataColumnsof the anonymous type and fill that.You see that it’s not that easy. There’s one dynamic approach though. But that requires reflection, therefore it’s not efficient at all.
Here we go… (extract of my other answer)
You could build your own CopyToDataTable that takes any kind of IEnumerable(not only
DataRow)and returns a newDataTable:Here is the implementation (with help of MSDN):
Now you can add these extensions:
Voilà! Now
CopyToDataTableworks with any kind ofIEnumerable<T>🙂