0

I'm joining two tables and I need to return flat collection of joined records. Here is initial code:

var v = (from t1 in Table1
         join t2 in Table2 on t1.Col1 equals t2.Col1
         select new {
             t1,
             t2
         }).ToList();

The result is a collection of 2 DataRow elements per row and is not flat. I want to efficiently flatten this so I could use it as DataSource for DataGridView. I can't list out each property of each element.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
ArtK
  • 1,157
  • 5
  • 17
  • 31

1 Answers1

1

There isn't really a "efficiently flatten" for DataRows because they are tightly coupled to the DataTable they belong to. A DataRow has no concept of the columns it contains, only the DataTable knows that. This is part of the reason mixing legacy DataSet/Table/Row code with Linq can be a problem. OTOH, Linq itself doesn't have a good way to flatten when combining either.

So, you have to create a DataTable that can hold all the Columns from both source tables and then copy the values in.

This answer has a further explanation and code: Combine DataTables

var BothTables = Table1.Clone();
BothTables.Columns.AddRange(Table2.Columns.OfType<DataColumn>()
   .Select(dc => new DataColumn(dc.ColumnName, dc.DataType, dc.Expression, dc.ColumnMapping)).ToArray());

foreach (var vr in v)
    BothTables.Rows.Add(vr.t1.ItemArray.Concat(vr.t2.ItemArray).ToArray());

var combinedv = BothTables.Rows;
Community
  • 1
  • 1
NetMage
  • 26,163
  • 3
  • 34
  • 55