Initial
list = { null, 1, 2, null, null, null, 4, 5, 6 };
Expecatiton
list = { null, 1, 2, null, 4, 5, 6 };
CodePudding user response:
If list
is an obsolete ArrayList
or List<oblect>
you can try a simple for
loop:
var list = new ArrayList { null, 1, 2, null, null, null, 4, 5, 6 };
int index = 0;
// Remove consequent null's
for (int i = 1; i < list.Count; i)
if (list[i] != null || list[index] != null)
list[index ] = list[i];
list.RemoveRange(index, list.Count - index);
To get rid of duplicates
int index = 0;
for (int i = 1; i < list.Count; i)
if (list[i] != list[index])
list[index ] = list[i];
list.RemoveRange(index, list.Count - index);
CodePudding user response:
When you are removing items from a list, loop it backwards, so that the indexes of the not yet processed items remains the same.
if (list.Count >= 2) {
for (int i = list.Count - 1; i > 0; i--) {
if (list[i] == list[i - 1]) {
list.RemoveAt(i);
}
}
}