Eliminate consecutive duplicates of list elements

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

    You can do it in LINQ:

    list.Aggregate(new List(), 
       (current, next) => {
          if (current.Length <= 0 || current[current.Length-1] != next) current.Add(next);
          return current;
       });
    

    Essentially, this creates an initially-empty list, runs through the entire source list, and only add an item to the target list if it is not the same as the last item of the target list.

    You can just as easily (probably easier) do it without LINQ:

    var target = new List();
    foreach (var item in list) {
       if (target.Length <= 0 || target[target.Length-1] != item) target.Add(item);
    }
    

提交回复
热议问题