Harshit
Harshit

Reputation: 5157

Remove all rows from the datatable except last one

As the title says, i have a datatable, now i want to remove all the rows in the datatable except the last one. I know there can be many complex ways to do so, but i would like to know the short & efficient way to do this task.

Upvotes: 1

Views: 6120

Answers (5)

Heinzi
Heinzi

Reputation: 172408

var lastRow = myDataTable.AsEnumerable().Last();
var newDataTable = new[] {lastRow}.CopyToDataTable();

Advantages:

  • Using Last() makes your intent absolutely clear and you cannot get any indexes wrong.
  • The original data table is not modified.

Disadvantages:

  • Bad performance (O(n) iteration through the list).
  • Creates a new data table instead of modifying the old one in-place.
  • Only the columns are kept, all other table properties (e.g. constraints) are not carried over to the new data table.

Reference:

Upvotes: 4

Tim Schmelter
Tim Schmelter

Reputation: 460238

You could use a backwards for-loop + RemoveAt:

for (int i = dataTable.Rows.Count - 2; i >= 0; i--)
    dataTable.Rows.RemoveAt(i);

Upvotes: 3

JunaidKirkire
JunaidKirkire

Reputation: 918

You could try doing this with a simple for loop as below

foreach (DataRow dr in ds.Tables[0].Rows)
{ 
    if(!dr.Equals(ds.Tables[0].AsEnumerable().Last()))
    {
       ds.Tables[0].Rows.Remove(dr);
    }
}

Upvotes: 0

stefankmitph
stefankmitph

Reputation: 3306

dataTable = dataTable.AsEnumerable().Skip(dataTable.Rows.Count - 1).CopyToDataTable();

Upvotes: 2

Dominic Scanlan
Dominic Scanlan

Reputation: 1009

DataRow dr = dt.Rows[dt.Rows.Count -1];

dt.Rows.Clear();
dt.Rows.Add(dr);

Upvotes: 3

Related Questions