Here's an approach which is relatively simple, only iterates once over the sequence, and works with any sequence (not just lists):
public IEnumerable<T> FindConsecutiveDuplicates<T>(this IEnumerable<T> source)
{
using (var iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
yield break;
}
T current = iterator.Current;
while (iterator.MoveNext())
{
if (EqualityComparer<T>.Default.Equals(current, iterator.Current))
{
yield return current;
}
current = iterator.Current;
}
}
}
Here's another one which is even simpler in that it's only a LINQ query, but it uses side-effects in the Where clause, which is nasty:
IEnumerable<int> sequence = ...;
bool first = true;
int current = 0;
var result = sequence.Where(x => {
bool result = !first && x == current;
current = x;
first = false;
return result;
});
A third alternative, which is somewhat cleaner but uses a SelectConsecutive
method which is basically SelectPairs
from this answer, but renamed to be slightly clearer :)
IEnumerable<int> sequence = ...;
IEnumerable<int> result = sequence.SelectConsecutive((x, y) => new { x, y })
.Where(z => z.x == z.y);