Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 584
Ian G Avatar asked Jan 19 '11 11:01

Ian G


1 Answers

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

like image 71
Theun Arbeider Avatar answered Sep 28 '22 04:09

Theun Arbeider