简体   繁体   中英

How do I limit the number of rows in a datatable?

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

The first thing to try is to NOT load too many rows into the DataTable. Is that possible?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM