Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to remove duplicate content in list?

Tags:

c#

.net

linq

Suppose I have this list:

int[] list = { 1, 2, 3, 3, 1 };

What I would like is to remove duplicates that immediately follow same number. So in this case I want to remove 3, but not 1.

New list should therefore be: {1, 2, 3, 1}

Another example is this list: {2, 7, 7, 7, 2, 6, 4} which will become {2, 7, 2, 6, 4}.

Can I do this with LINQ?

like image 856
brinch Avatar asked Dec 31 '25 10:12

brinch


1 Answers

You could use Aggregate if you want to use an existing LINQ method but such an approach would lose laziness. You can write your own extension method:

public static IEnumerable<T> RemoveConsecutiveDuplicates<T>(this IEnumerable<T> source, IEqualityComparer<T> comp = null)
{
    comp = comp ?? EqualityComparer<T>.Default;

    using (var e = source.GetEnumerator())
    {
        if (e.MoveNext())
        {
            T last = e.Current;
            yield return e.Current;

            while (e.MoveNext())
            {
                if (!comp.Equals(e.Current, last))
                {
                    yield return e.Current;
                    last = e.Current;
                }
            }
        }
    }
}
like image 90
Lee Avatar answered Jan 05 '26 22:01

Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!