用设定值替换连续的重复项,但前提是连续范围的长度超过阈值

Replace contiguous duplicates by a set value, but only if length of contiguous range more than a threshold

用另一个给定值替换列表元素中连续的相同值的有效方法是什么,但前提是连续序列运行超过一定数量的元素(例如:多于或等于 5)

示例:

["red"; "red"; "blue"; "green"; "green"; "red"; "red"; "red"; "red"; "red"; "red"; "yellow"; "white"; "white"; "red"; "white"; "white"]

应该变成:

["red"; "red"; "blue"; "green"; "green"; "ignore"; "ignore"; "ignore"; "ignore"; "ignore"; "ignore"; "yellow"; "white"; "white"; "red"; "white"; "white"]

有什么想法吗?

如评论中所述,使用 GroupAdjacent to group contiguous duplicates using the nuget package MoreLinq 是一种选择:

var strings = new List<string> { "red", "red", "blue", "green", "green", "red", "red", "red", "red", "red", "red", "yellow", "white", "white", "red", "white", "white" };

var result = strings
    .GroupAdjacent(x => x)
    .SelectMany(grp => (grp.Count() >= 5) ?
                grp.Select(x => "ignore") : 
                grp);

Console.WriteLine("{ " + string.Join(", ", result) + " }");

结果:

{ red, red, blue, green, green, ignore, ignore, ignore, ignore, ignore, ignore, yellow, white, white, red, white, white }

上面也使用了Enumerable.SelectMany to flatten the grouped IEnumerable<IEnumerable<string>> sequence into a IEnumerable<string>, and then a ternary operator to decide if the group should be completely replaced by "ignore" with Enumerable.Select if the group length from Enumerable.Count大于或等于5,或者保持原样。