How to assign a row collection (obtained by a linq query) to a datatable without using a loop?
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 us开发者_运维百科ing 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.
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
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();
精彩评论