How to limit the number of rows in a datatable?

I generate a DataTable ( from non-SQL data ) and then use a DataView to filter records.

I want to limit the number of records in the final set of records , but I can not do this when I create a DataTable .

I resorted to deleting rows from the final result set:

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?

+4
source share
4 answers

You can use Linq:

Try changing the 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 will need a namespace: System.Linq and System.Data p>

+4
source

The first thing to try: DO NOT load too many rows in a DataTable. Is it possible?

+1
source

Can you add a column that will be similar, like rowcount 1,2,3 Something like incrementing when you add rows from Non-SQL data to datatable. You can probably use after that

 DataRow[] rows1 = dTable.Select(" RowIncrement < 50", "EventDate ASC"); 

RowIncrement is a column that will look like ROWNUM

0
source

Try copying the top rows x from one data type to a new one.

 dataTable.AsEnumerable().Take(50).CopyToDataTable(newdataTable) 

and then use this.

0
source

Source: https://habr.com/ru/post/1336123/


All Articles