C# 从数据表中选择第二组 20 行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14717644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting second set of 20 row from DataTable
提问by DMckendrick
I have a DataTable I am populating from SQL table with the following example columns
我有一个 DataTable 我正在从 SQL 表中填充以下示例列
- ID
- Type
- Value
- ID
- 类型
- 价值
I am populating the DataTable with rows which are of a certain type. I want to select the rows 10 - 20 from my resulting DataTable:
我正在用某种类型的行填充 DataTable。我想从生成的 DataTable 中选择第 10 - 20 行:
Connect conn = new Connect();
SqlDataAdapter da = new SqlDataAdapter(SQL, conn.Connection());
//Creates data
DataTable d = new DataTable();
da.Fill(d);
DataRow[] result = d.Select();
In the above code I have omitted the main SQL, and currently I have no select for my DataRow array. I cannot find a way to reference the row numbers.
在上面的代码中,我省略了主要的 SQL,目前我的 DataRow 数组没有选择。我找不到引用行号的方法。
So for instance I am looking for something like Select("rownum > X && rownum < Y")
所以例如我正在寻找类似的东西 Select("rownum > X && rownum < Y")
I have searched here, and a number of other resources to no avail. Any clues would be really handy, or just a simple not possible.
我在这里搜索过,还有一些其他资源无济于事。任何线索都会非常方便,或者只是简单的不可能。
采纳答案by Tim Schmelter
It's always better to select only what you need from the database(f.e. by using the TOP
clause or a window function like ROW_NUMBER
) instead of filtering it in memory.
最好只从数据库中选择您需要的内容(通过使用TOP
子句或窗口函数,如ROW_NUMBER
),而不是在内存中过滤它。
However, you can use Linq-To-DataSet
and Enumerable.Skip
+ Enumerable.Take
:
但是,您可以使用Linq-To-DataSet
和Enumerable.Skip
+ Enumerable.Take
:
var rows = d.AsEnumerable()
.Skip(9).Take(11); // select rows 10-20 as desired (so you want 11 rows)
If you want a new DataTable
from the filtered result use CopyToDataTable
, if you want a DataRow[]
use rows.ToArray()
.
如果你想要一个新DataTable
的过滤结果使用CopyToDataTable
,如果你想要一个DataRow[]
使用rows.ToArray()
。
回答by djangojazz
I would just do the 'take' and 'skip' command and keep it simple:
我只会执行 'take' 和 'skip' 命令并保持简单:
d.Select().Skip(10).Take(10); // skips 10 rows, then selects ten after that.
This would be assuming you have the Linq using set (using System.Linq)
这将假设您拥有使用 set 的 Linq(使用 System.Linq)