I generate a DataTable (from non-SQL data) and then use a DataView to filter the records.
I want to limit the number of records in the final record set but can't do this when I generate the DataTable.
I've resorted to deleting rows from the final result set, as per:
DataView dataView = new DataView(dataTable);
dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
dataView.Sort = "EventDate";
dataTable = dataView.ToTable();
while (dataTable.Rows.Count > _rowLimit)
dataTable.Rows[dataTable.Rows.Count - 1].Delete();
return dataTable;
Is there a more efficient way to limit the results?
You can use Linq:
Try changing your code to the following:
DataView dataView = new DataView(dataTable);
dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
dataView.Sort = "EventDate";
dataTable = dataView.ToTable();
while (dataTable.Rows.Count > _rowLimit)
{
dataTable = dataTable.AsEnumerable().Skip(0).Take(50).CopyToDataTable();
}
return dataTable;
You'll need namespace: System.Linq and System.Data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With