How to assign a row collection (obtained by a linq query) to a datatable without using a loop?

StackOverflow https://stackoverflow.com/questions/6342291

  •  27-10-2019
  •  | 
  •  

Question

I've scenario where the datatable may contain large number of rows. As a result i can't iterate and update the datatable using a loop.

I am using the following code to get row collection,

         from row in CSVDataTable.AsEnumerable()
         where CSVDataTable.Columns.Cast<DataColumn>().Any(col => !row.IsNull(col))
         select row;

Any one please tell me how to assign the result of the above code to a datatable without using a loop.

Was it helpful?

Solution

I could assign the Linq query result to a data table by the following code,

           // Create a DataTable from Linq query.       

             IEnumerable<DataRow> query = from row in CSVDataTable.AsEnumerable()
                                            where CSVDataTable.Columns.Cast<DataColumn>().Any(col => !row.IsNull(col))
                                            select row; //returns IEnumerable<DataRow>

             DataTable CSVDataTableWithoutEmptyRow = query.CopyToDataTable<DataRow>();

See the link for further details,

http://msdn.microsoft.com/en-us/library/bb386921.aspx

OTHER TIPS

You are trying to avoid the unavoidable I think.

You have a "lazy" query wich returns an IEnumerable<DataRow>. This query will be enumerated no matter what when you try to access the DataRow collection it represents.

The only difference will be if you do it directly or some method of DataTable hides that implementation detail.

I'd do the following:

DataTable table;
table.BeginLoadData();
foreach (DataRow row in query)
{
     table.ImportRow(row);
}
table.EndLoadData();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top