简体   繁体   English

如何限制数据表中的行数?

[英]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. 我生成一个DataTable( 来自非SQL数据 ),然后使用DataView过滤记录。

I want to limit the number of records in the final record set but can't do this when I generate the DataTable . 我想限制最终记录集中的记录数, 但是在生成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: 你可以使用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 您将需要命名空间:System.Linq和System.Data

The first thing to try is to NOT load too many rows into the DataTable. 首先要尝试的是不要在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. 您是否可以添加一个类似于rowcount 1,2,3的列,当您将非SQL数据中的行添加到数据表时,会增加一些内容。 Probably after that you can use 可能之后你可以使用

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

RowIncrement is the column which would be something like ROWNUM RowIncrement是一个类似于ROWNUM的列

Try copying the top x rows from one datatable into a new one. 尝试将顶部x行从一个数据表复制到一个新数据表中。

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

and then use that. 然后使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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