Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove contiguous duplicates in the sequence of objects [duplicate]

Tags:

c#

.net

algorithm

suppose we have the list of objects

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

what is the most elegant way to get the following result list?

{1,2,3,2,1}
like image 968
Alex Avatar asked Dec 04 '25 11:12

Alex


2 Answers

I like the idea of an extension method:

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;
    }
}

And then, of course, to use it:

var singles = list.RemoveContiguousDuplicates().ToList();
like image 136
itsme86 Avatar answered Dec 07 '25 00:12

itsme86


Try this:

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
}
like image 38
Salah Akbari Avatar answered Dec 06 '25 23:12

Salah Akbari