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 t开发者_Go百科here 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
Can you add a column which will be similar like rowcount 1,2,3 Something like incrementing as you add rows from your Non-SQL data to the datatable. Probably after that you can use
DataRow[] rows1 = dTable.Select(" RowIncrement < 50", "EventDate ASC");
RowIncrement is the column which would be something like ROWNUM
Try copying the top x rows from one datatable into a new one.
dataTable.AsEnumerable().Take(50).CopyToDataTable(newdataTable)
and then use that.
精彩评论