Here's how to do it in a simple LINQ:
int[] source = new[] { 3, 6, 1, 8, 4, 1, 1, 1, 7, 4, 2, 2 }; var result = source.Where((x, i) => i == 0 || !x.Equals(source.ElementAt(i - 1)));
However, this code should be used only when the base sequence implements an effective index to handle the call to ElementAt , ideally O (1) times. This usually applies to implementations of IList<T> , such as arrays, but not to other collections, such as LinkedList<T> .
In addition, if you need to regularly use this functionality, there is nothing wrong with defining an extension method that is more convenient than scattering this code (or any equivalent) throughout. I personally would prefer to use my own extension method to avoid the risk of performance issues for non-indexed collections.
source share