4

How do I get the last 5 rows of a datatable? I tried something like this:

var Long_bottom = LongSlection.Last(5);

Where LongSlection is a DataRow. But I had an error, any idea?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
francops henri
  • 507
  • 3
  • 17
  • 29

4 Answers4

5

Not sure what you have got here

var Long_bottom = LongSlection.Last(5);

Assuming you have a DataTable and you want to get the last 5 rows you can do that via

datatable1.AsEnumerable().Reverse().Take(5);

Take and Skip return the specific number of elments (parameter is int) while which is not the case with Last you get the last element or you need a predicate for checking conditions or checks within the row.

V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
0

This SHOULD do it. but it's untested!

IEnumerable<DataRow> lastRows = table.AsEnumerable().Skip(table.Rows.Count - 2).ToList();

Or:

table.AsEnumerable().Reverse().Take(2);

Edit: Modified to get the last TWO, as per the OPs request.

Faraday
  • 2,904
  • 3
  • 23
  • 46
0

How about

Datarow[] dr = dt.Rows.Cast<DataRow>().Skip(dt.Rows.Count - 5).ToArray();

OR

dt.Rows.Cast<DataRow>().Reverse().Take(5);

Here 5 is the last number of rows to take.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
0

I needed CopyToDataTable() to get things done:

dt = dt.AsEnumerable().Reverse().Take(5).CopyToDataTable();
Mamun
  • 66,969
  • 9
  • 47
  • 59