My aim is to : linq-join two c# DataTables and to select all columns from the first table(without enumerating the columns) and only 1 column from the second and obtain result as DataTable:
var result = from t in tt.AsEnumerable() join a in aa.AsEnumerable() on t.Field<DateTime>("time") equals a.Field<DateTime>("time")
select new { t, aa_col1 = a.Field<int>("col1") }
;
YET the result of that join can't be converted to DataTable.
The underlying idea of the issue is : not to enumerate all columns of tt manually while composing linq-join ( the number of tt columns may be large and dynamic)
I tried to solve the problem applying result.CopyToDataTable() method , but the compiler produced error: Type < anonymous type System.Data.DataRow t , int aa_col1> can't be used as parameter of type T in universal method "DataTableExtensions.CopyToDataTable(IEnumerable)"
Beneath is shown the code for the test tables tt and aa:
DataTable tt = new DataTable();
tt.Columns.Add("time", typeof(DateTime));
tt.Columns.Add("col1", typeof(int));
tt.Columns.Add("col2", typeof(int));
tt.Columns.Add("col3", typeof(int));
DataRow dr = tt.NewRow();
dr["time"] = new DateTime(2018,10,5); dr["col1"] = 24; dr["col2"] = 14; dr["col3"] = 15;
tt.Rows.Add(dr);
dr = tt.NewRow();
dr["time"] = new DateTime(2018, 10, 6); dr["col1"] = 4; dr["col2"] = 43; dr["col3"] = 58;
tt.Rows.Add(dr);
dr = tt.NewRow();
dr["time"] = new DateTime(2018, 10, 6); dr["col1"] = 6; dr["col2"] = 3; dr["col3"] = 78;
tt.Rows.Add(dr);
dr = tt.NewRow();
dr["time"] = new DateTime(2018, 10, 7); dr["col1"] = 1; dr["col2"] = 4; dr["col3"] = 5;
tt.Rows.Add(dr);
// -----
DataTable aa = new DataTable();
aa.Columns.Add("time", typeof(DateTime));
aa.Columns.Add("col1", typeof(int));
aa.Columns.Add("col2", typeof(int));
aa.Columns.Add("col3", typeof(int));
DataRow rr = aa.NewRow();
rr["time"] = new DateTime(2018, 10, 4);
rr["col1"] = 6; rr["col2"] = 34; rr["col3"] = 66;
aa.Rows.Add(rr);
rr = aa.NewRow();
rr["time"] = new DateTime(2018, 10, 5); rr["col1"] = 7; rr["col2"] = 43; rr["col3"] = 98;
aa.Rows.Add(rr);
rr = aa.NewRow();
rr["time"] = new DateTime(2018, 10, 6); rr["col1"] = 6; rr["col2"] = 3; rr["col3"] = 3;
aa.Rows.Add(rr);
rr = aa.NewRow();
rr["time"] = new DateTime(2018, 10, 7); rr["col1"] = 16; rr["col2"] = 65; rr["col3"] = 12;
aa.Rows.Add(rr);
The linq-join produces the type : {System.Linq.Enumerable.d__38f__AnonymousType0>}
See the figures showing "var result" in detail:
https://yadi.sk/i/X8K9HIq5hnavCg
and
https://yadi.sk/i/MaViq23zqpRDXw
and
https://yadi.sk/i/Re0DFJdVl02RjA
The target result of join should be a table that contains all columns from tt and first column of aa - aa.col1 :
time col1 col2 col3 aa_col1
05.10.2018 0:00 24 14 15 7
06.10.2018 0:00 4 43 58 6
06.10.2018 0:00 6 3 78 6
07.10.2018 0:00 1 4 5 16