我有一个看起来像这样的项目列表:
let myList = [ "One"; "Two"; "Three and Four"; "Five"; "and Six"; "Seven and"; "Nine and Ten and Eleven" ]
Run Code Online (Sandbox Code Playgroud)
我需要将包含单词的每个项目拆分and
为单独的项目,然后将它们重新插入列表,同时保持顺序。有没有什么优雅有效的方法来做到这一点?目前我正在使用循环和可变列表进行聚合:
let mutable result = []
for item in myList do
let split = item.Split("and", StringSplitOptions.RemoveEmptyEntries)
for subItem in split do
result <- subItem::result
List.rev result
Run Code Online (Sandbox Code Playgroud)
我怀疑有更好的方法来做到这一点(更多功能,更少的 C#-y),但我不知道如何去做。
小智 7
一些更擅长 FP 的人可能会来改进这一点,因为我还在学习东西,但这是我的看法。
let myList = [ "One"; "Two"; "Three and Four"; "Five"; "and Six"; "Seven and"; "Nine and Ten and Eleven" ]
myList
|> Seq.collect (fun x -> x.Split("and", StringSplitOptions.RemoveEmptyEntries))
|> Seq.toList
Run Code Online (Sandbox Code Playgroud)