Eliminate consecutive duplicates of list elements

前端 未结 11 1558
南笙
南笙 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 02:56

    Resolution:

    IList stringList = new List() { "red", "red", 
                                                    "blue", "green", 
                                                    "green", "red", 
                                                    "red", "yellow", 
                                                    "white", "white", 
                                                    "red", "white", "white" };      
      for (int i = 0; i < stringList.Count; i++)
      {
        // select the first element
        string first = stringList[i];
    
        // select the next element if it exists
        if ((i + 1) == stringList.Count) break;
        string second = stringList[(i + 1)];
    
        // remove the second one if they're equal
        if (first.Equals(second))
        {
          stringList.RemoveAt((i + 1));
          i--;
        }
      }
    

    correct me in the comments if something is wrong please!

    /e: Edited code so it works on "white","white","white","white"

提交回复
热议问题