Eliminate consecutive duplicates of list elements

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

    Here is my suggestion. It is similar to @AlexJ's answer, with the addition of an IEqualityComparer parameter that allows to customize the equality check. I also removed the otherwise correct separation of argument-check and implementation, because this solution is not intended to be of Library-grade quality. As for the name I adopted the ExcludeConsecutiveDuplicates from @AntonSemenov's answer.

    public static IEnumerable ExcludeConsecutiveDuplicates(
        this IEnumerable source, IEqualityComparer comparer = null)
    {
        if (source == null) throw new ArgumentNullException(nameof(source));
        comparer = comparer ?? EqualityComparer.Default;
        bool isFirst = true;
        TSource last = default;
        foreach (var item in source)
        {
            if (isFirst || !comparer.Equals(item, last)) yield return item;
            isFirst = false;
            last = item;
        }
    }
    

    Usage example:

    var source = new string[]
    {
        "Red", "red", "blue", "green", "green", "red", "red", "yellow",
        "WHITE", "white", "red", "white", "white"
    };
    var result = source.ExcludeConsecutiveDuplicates(StringComparer.OrdinalIgnoreCase);
    Console.WriteLine($"Result: {String.Join(", ", result)}");
    

    Output:

    Result: Red, blue, green, red, yellow, WHITE, red, white
    

    The advantage of this solution compared to the accepted answer is that it doesn't require a source of type IList to be efficient.

提交回复
热议问题