It doesn't remove non-adjacent duplicate values.
You have a bug in your loops. The indexes are not accounting for the fact the collection is changing due to the Delete
call.
You're also doing more work than necessary by going through all rows multiple times.
This creates a list of DevExpress Row
objects that need to be deleted. And it only goes through the rows once.
//Let's keep track of every value seen as we go through the rows
var valuesSeen = new HashSet<string>();
//Rows marked for deletion
var duplicateRows = new List<Row>();
for (int i = 0; i < LastRow; i++)
{
string cellValue = worksheet.Cells[i, 0].DisplayText;
//Returns false if the value already exists
if (!valuesSeen.Add(cellValue))
{
//Mark this row for deletion since we've seen the value before
duplicateRows.Add(worksheet.Rows[i]);
}
}
//Delete all marked rows only after we're done identifying them.
foreach (var row in duplicateRows)
row.Delete();
You may need to specify the namespace for Row
given it's a fairly common class name.
In the above code I'm comparing the display text (not actual value). Use HashSet<CellValue>
instead of HashSet<string>
if you don't want this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…