C# 删除对象序列中连续的重复项

C# 删除对象序列中连续的重复项,c#,.net,algorithm,C#,.net,Algorithm,假设我们有对象列表 List<int> list = new List<int>() { 1,1,1,2,3,3,3,2,2,2,1,1 }; 试试这个: List<int> newList = new List<int>(); foreach (var item in list.Where(c => newList.Count == 0 || newList.Last() != c)) { newList.Add(item); /

假设我们有对象列表

List<int> list = new List<int>() { 1,1,1,2,3,3,3,2,2,2,1,1 };
试试这个:

List<int> newList = new List<int>();
foreach (var item in list.Where(c => newList.Count == 0 || newList.Last() != c))
{
    newList.Add(item); // 1,2,3,2,1 will add to newList
}
List newList=newList();
foreach(list.Where(c=>newList.Count==0 | | newList.Last()!=c)中的变量项)
{
newList.Add(item);//1,2,3,2,1将添加到newList
}

我喜欢扩展方法的想法:

public static IEnumerable<T> RemoveContiguousDuplicates<T>(this IEnumerable<T> items) where T: IEquatable<T>
{
    bool init = false;
    T prev = default(T);

    foreach (T item in items)
    {
        if (!init)
            init = true;
        else if (prev.Equals(item))
            continue;

        prev = item;
        yield return item;
    }
}

假设列表包含可以使用的基本类型。e、 g:
list.Distinct().ToList()。如果您的列表包含复杂类型,则需要向其传递一个
IEqualityComparer
您的类型implements@sstan请阅读我的问题bettera并删除“标记为重复”或提供有效答案您想要的结果
{1,2,3,2,1}
与您的要求不匹配
删除对象序列中的重复项
这将根据您的数据集为您提供
1,2,3
的结果。您可以使用类似var requiredList=list的内容。其中((value,index)=>index==0 | | value!=list.ElementAt(index-1))@阿伦兰姆,谢谢,它解决了问题
public static IEnumerable<T> RemoveContiguousDuplicates<T>(this IEnumerable<T> items) where T: IEquatable<T>
{
    bool init = false;
    T prev = default(T);

    foreach (T item in items)
    {
        if (!init)
            init = true;
        else if (prev.Equals(item))
            continue;

        prev = item;
        yield return item;
    }
}
var singles = list.RemoveContiguousDuplicates().ToList();