3

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}
itsme86
  • 19,266
  • 4
  • 41
  • 57
Alex
  • 93
  • 1
  • 4
  • Assuming your list contains primitive types you can use [Distinct()](https://msdn.microsoft.com/en-us/library/vstudio/bb348436(v=vs.100).aspx). e.g: `list.Distinct().ToList();`. If your list contains complex types you'll need to pass it an `IEqualityComparer` which your type implements – DGibbs Oct 20 '15 at 15:59
  • 6
    @sstan please read my question bettera and remove "marked as duplicate" or provide a valid answer – Alex Oct 20 '15 at 16:07
  • Your desired outcome `{1,2,3,2,1}` doesn't match your requirements `remove duplicates in the sequence of objects` which would give you a result of `1, 2, 3` based on your dataset. – DGibbs Oct 20 '15 at 16:12
  • 3
    You can use something like var requiredList = list.Where((value, index) => index == 0 || value != list.ElementAt(index - 1)); – arunlalam Oct 20 '15 at 16:24
  • @arunlalam, thanks , it solves the problem – Alex Oct 20 '15 at 16:41

2 Answers2

6

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();
itsme86
  • 19,266
  • 4
  • 41
  • 57
2

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
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109