Choosing a second set of 20 rows from a DataTable

I have a DataTable that I populate from an SQL table with the following example columns

  • ID
  • Type of
  • Value

I populate a DataTable with rows of a specific type. I want to select rows 10-20 from my resulting DataTable:

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 code above, I skipped the main SQL, and currently I have no choice for my DataRow array. I cannot find a way to refer to line numbers.

So, for example, I'm looking for something like Select("rownum > X && rownum < Y")

I searched here for a number of other resources to no avail. Any tips will be really convenient or simply impossible.

+8
c # select datatable
source share
2 answers

It is always better to select only what you need from the database (for example, using the TOP clause or a window function such as ROW_NUMBER ), instead of filtering in memory.

However, you can use Linq-To-DataSet and 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 the new DataTable from the filtered result to use CopyToDataTable , if you want to use DataRow[] rows.ToArray() .

+14
source share

I would simply execute the take and skip command and save it simply:

  d.Select().Skip(10).Take(10); // skips 10 rows, then selects ten after that. 

This assumes you have Linq using set (using System.Linq)

+5
source share

All Articles