Reputation: 5157
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
Reputation: 172408
var lastRow = myDataTable.AsEnumerable().Last();
var newDataTable = new[] {lastRow}.CopyToDataTable();
Advantages:
Last()
makes your intent absolutely clear and you cannot get any indexes wrong.Disadvantages:
O(n)
iteration through the list).Reference:
Upvotes: 4
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
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
Reputation: 3306
dataTable = dataTable.AsEnumerable().Skip(dataTable.Rows.Count - 1).CopyToDataTable();
Upvotes: 2
Reputation: 1009
DataRow dr = dt.Rows[dt.Rows.Count -1];
dt.Rows.Clear();
dt.Rows.Add(dr);
Upvotes: 3