swallis1
swallis1

Reputation: 99

C# Copy DataTable from index[x] to end

I am loading a dataset from an excel file. I grab the first table as DataTable table. I want to return a datatable that starts at the int startingIndex. I want to do something like:

DataTable table = GetDtFromFile();
DataTable results;
table.Rows.CopyTo(results, startingIndex);
return results;

The only solutions for this I see are using for loops to loop through every row after the startingIndex and copy rows over individually. This seems silly and unnecessary.

Any tricks out there I'm not seeing on how to do this? Thanks!


Other Attempts:

DataTable table = GetDtFromFile();
DataTable results;
int size = table.Rows.Count - startingRow;
DataRow[] temp = new DataRow[size];
table.Rows.CopyTo(temp, startingRow);
results.Rows = temp;

This has an error on results.Rows that DataTable.Rows is read only. (This also seems unnecessarily complicated).

Upvotes: 0

Views: 498

Answers (1)

swallis1
swallis1

Reputation: 99

Thank you linq!

Answer:

DataTable table = GetDtFromFile();
DataTable results;
int startingRow = GetStartingRow();
int size = table.Rows.Count - startingRow;
results = table.AsEnumerable().Skip(startingRow).Take(size).CopyToDataTable();

Upvotes: 3

Related Questions