什么是用另一个给定值替换列表元素中的连续相同值的有效方法,但前提是连续序列运行的元素数量超过一定数量(例如:大于或等于5)>
示例:
[“红色”; “红色”; “蓝色”; “绿色”; “绿色”; “红色”; “红色”; “红色”; “红色”; “红色”; “红色”; “黄色”; “白色”; “白色”; “红色”; “白色”; “白色”]
应成为:
[“红色”; “红色”; “蓝色”; “绿色”; “绿色”; “忽略”; “忽视” ; “忽视”; “忽视”; “忽视”; “ ignore”; “黄色”; “白色”; “白色”; “红色”; “白色”; “白色”]
有什么主意吗?
答案 0 :(得分:3)
如评论中所述,使用GroupAdjacent
使用nuget包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
将已分组的IEnumerable<IEnumerable<string>>
序列展平为IEnumerable<string>
,然后使用三元运算符来确定是否应将组完全替换为"ignore"
如果Enumerable.Select
中的组长度大于或等于5 ,或者保持原样,则使用Enumerable.Count
。