Eliminate consecutive duplicates of list elements

前端 未结 11 1557
南笙
南笙 2020-12-03 02:31

Is there a \"nice\" way to eliminate consecutive duplicates of list elements?

Example:

[\"red\"; \"red\"; \"blue\"; \"green         


        
11条回答
  •  清歌不尽
    2020-12-03 03:15

    Like this you don't need a new object.

    public static void RemoveConsecutiveDuplicates(this List collection)
    {
        for (int i = 0; i < collection.Count - 1; i++)
        {
            if (collection[i].Equals(collection[i + 1]))
            {
                collection.RemoveAt(i);
                i--;
            }
        }
    }
    
    var collection = new [] { 2, 7, 7, 7, 2, 6, 4 }.ToList();
    collection.RemoveConsecutiveDuplicates();
    

提交回复
热议问题