0

I am joining datatables to create a new datatable,

Code :

var row = from r0w1 in dt_vi.AsEnumerable()
              join r0w2 in dt_w.AsEnumerable()
              on r0w1.Field<int>("ID") equals r0w2.Field<int>("iD")
              join r0w3 in dt_re.AsEnumerable()
              on r0w1.Field<int?>("ID") equals r0w3.Field<int?>("id")
              join r0w4 in dt_def.AsEnumerable()
              on r0w1.Field<int?>("ID") equals r0w4.Field<int?>("id") into ps
              from r0w4 in ps.DefaultIfEmpty()
              select r0w1.ItemArray.Concat(r0w2.ItemArray.Concat(r0w3.ItemArray.Concat(r0w4 != null ? r0w4.ItemArray : new object[] { }))).ToArray();


foreach (object[] values in row)
    dt.Rows.Add(values);

In the above code,

foreach (object[] values in row)
    dt.Rows.Add(values);

is slow for hundreds of thousands of rows. I want to put the data of row into dt

I want to know if there is any way exists so, that I don't have to use loop to create a new datatable ?

James Z
  • 12,209
  • 10
  • 24
  • 44
Harshit
  • 5,147
  • 9
  • 46
  • 93
  • I think that you need the datatable.Merge method here. – Thanos Markou Dec 10 '15 at 09:48
  • 1
    What is " thousand hundreds"? Do you mean "hundred thousand", what means _slow_? In general LINQ also uses loops and there is no other way to fill your table (even `DataTable.Merge` uses a loop). – Tim Schmelter Dec 10 '15 at 10:00
  • @TimSchmelter, LINQ seems to use some better way of looping, since I always found LINQs faster than my loops. – Harshit Dec 10 '15 at 10:04
  • @HarshitShrivastava: yes, a `Join` uses a set based approach which is not exactly a loop and [is more efficient in most cases](http://stackoverflow.com/questions/5551264/why-is-linq-join-so-much-faster-than-linking-with-where). But that's just the query. If you want to fill a fifth table with the results you need a loop. – Tim Schmelter Dec 10 '15 at 10:06
  • Why not using [CopyToDataTable](https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k(System.Data.DataTableExtensions.CopyToDataTable%60%601);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5.2);k(DevLang-csharp)&rd=true)? – Hamid Pourjam Dec 10 '15 at 10:08
  • I tried `dt=row.CopyToDataTable();` but it is giving error. – Harshit Dec 10 '15 at 10:11
  • You should use it on `IEnumerablewhere T : DataRow` – Hamid Pourjam Dec 10 '15 at 10:12

1 Answers1

1

As @Thanos Markow mentioned, you need to use dataTable.Merge(the second data table).

An Important Note: The merge operation takes into account only the original table, and the table to be merged. Child tables are not affected or included. If a table has one or more child tables, defined as part of a relationship, each child table must be merged individually.

israel altar
  • 1,768
  • 1
  • 16
  • 24