Reputation: 393
I currently have a datatable which is sorted by a specific column and once the sort has been done I would like to get rid of the rows of data which are not needed at the bottom,
For example, I have 14 rows and only need the top 10, how would I be able to delete the bottom four?
the datatable is queried from a falt file spread sheet file stored in a datatable and then i am sorting the data then only want to take the top 10 rows
Upvotes: 0
Views: 3949
Reputation: 216293
You could use Linq to extract the top 10 record using Take(10) but after you have sorted the datatable
var records = datatable.AsEnumerable().OrderBy(v => v["FieldToUseAsSortOrder"]).Take(10);
foreach(DataRow r in records)
{
// process your records in order
}
Of course this will redo the sort against your table, so it's up to you to choose between sorting through the LinQ expression above or loop on your DefaultView rows and remove the unneeded ones
for(int x = 10; x < datatable.DefaultView.Count; x++)
{
datatable.DefaultView[x].Row.Delete();
}
datatable.AcceptChanges();
The first approach leave your datatable with all the original rows extracting only the needed one, the second approach will update your datatable removing the unneeded rows (Only in memory of course)
Upvotes: 1
Reputation: 5439
if your database is Sql Server:
Delete From VictimTable
Where ID Not In(
Select Top 10 ID From VictimTable Order By SomeColumn)
Upvotes: 0