我正在寻找一种方法来防止列表中的重复项,但仍然保留顺序。例如:
1, 2, 3, 4, 4, 4, 1, 1, 2, 3, 4, 4
应该转变为
1, 2, 3, 4, 1, 2, 3, 4
我使用了一个for
循环,不太优雅地完成了这个任务,检查下一个项目的方法如下:
public static List<T> RemoveSequencialRepeats<T>(List<T> input)
{
var result = new List<T>();
for (int index = 0; index < input.Count; index++)
{
if (index == input.Count - 1)
{
result.Add(input[index]);
}
else if (!input[index].Equals(input[index + 1]))
{
result.Add(input[index]);
}
}
return result;
}
有没有更加优雅的方法来完成这个操作,最好使用LINQ?
List<T>.Add
可能非常依赖 GC... - Aron