Eliminate consecutive duplicates of list elements

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

    You can roll your own, linq-style.

    // For completeness, this is two methods to ensure that the null check 
    // is done eagerly while the loop is done lazily. If that's not an issue, 
    // you can forego the check and just use the main function.
    
    public static IEnumerable NonConsecutive(this IEnumerable input)
    {
      if (input == null) throw new ArgumentNullException("input");
      return NonConsecutiveImpl(input);
    }
    
    static IEnumerable NonConsecutiveImpl(this IEnumerable input)
    {
       bool isFirst = true;
       T last = default(T);
       foreach (var item in input) {
          if (isFirst || !object.Equals(item, last)) {
              yield return item;
              last = item;
              isFirst = false;
          }
       }
    }
    

    And use as

    array.NonConsecutive().ToArray()
    

    The advantage is that it's lazily evaluated, so you can use it on any enumeration without having to consume it in its entirety, and chain it with other linq methods (eg: array.Where(i => i != "red").NonConsecutive().Skip(1).ToArray()). If you don't have that requirement and you just want to work with arrays, something like Simon Bartlett's solution might be slightly more performant.

    For more information on why it has to be two methods, see here

提交回复
热议问题