Home > database >  how can I remove the duplicate value next to each other using linq
how can I remove the duplicate value next to each other using linq

Time:10-01

I have a list and I want to remove the duplicate value next to each other

var idList = new List<int>(){100,100,200,200,300,300,100,100,200,200,300,300}

and this is my expected result

[100,200,300,100,200,300]

how can I achieve this in linq

CodePudding user response:

You can use Aggregate in LINQ -

var idList = new List<int>() { 100, 100, 200, 200, 300, 300, 100, 100, 200, 200, 300, 300 };
var result = idList.Aggregate(new List<int>(), (current, next) => 
            {
                if (current.Count == 0 || current.Last() != next)
                {
                    current.Add(next);
                }
                return current;
           });

CodePudding user response:

You are asking for some custom distinct logic, The regular idList.Distinct() will return in your example [100,200,300] which is not what you asked for.

To achieve what you are asking for you can implement an extention method for Linq:

public static class LinqExtentions
{
    public static IEnumerable<T> CustomDistinct<T>(this IEnumerable<T> source)
    {
        int i = 0;
        foreach (T item in source)
        {
            if (i   1 < source.Count())
            {
                if (!item.Equals(source.ElementAt(i   1)))
                    yield return item;
            }
            else
            {
                //we reached the last item
                yield return item;
            }
            i  ;
        }
    }

}

And now you can use it like this:

var idList = new List<int>() { 100, 100, 200, 200, 300, 300, 100, 100, 200, 200, 300, 300 };
var list = idList.CustomDistinct().ToList();
  • Related