Eliminate consecutive duplicates of list elements

前端 未结 11 1542
南笙
南笙 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:01

    Try this:

    using System;    
    using System.Linq;    
    using System.Collections.Generic;
    
    namespace RemoveDuplicates
    {
        class MainClass
        {
            public static void Main (string[] args)
            {
    
                string[] a = new string[] 
                { "red", "red", "red", "blue", 
                          "green", "green", "red", "red", 
                          "yellow", "white", "white", "red", "white", "white" };
    
                for(int i = 0; i < a.Length; ++i)
                    if (i == a.Length-1 || a[i] != a[i+1])
                        Console.WriteLine(a[i]);
    
            }
        }
    }
    

    Output:

    red
    blue
    green
    red
    yellow
    white
    red
    white
    

提交回复
热议问题