When I use Console.WriteLine to print a list, it defaults to only showing the first three elements. How do I get it to print the entire contents of the list?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can use the %A format specifier along with printf to get a 'beautified' list printout, but like Console.WriteLine (which calls .ToString()) on the object, it will not necessarily show all the elements. To get them all, iterate over the whole list. The code below shows a few different alternatives.
let smallList = [1; 2; 3; 4]
printfn "%A" smallList // often useful
let bigList = [1..200]
printfn "%A" bigList // pretty, but not all
printfn "Another way"
for x in bigList do
printf "%d " x
printfn ""
printfn "Yet another way"
bigList |> List.iter (printf "%d ")
printfn ""
回答2:
You can iterate over the it, using the List.iter
function, and print each element:
let list = [1;2;3;4]
list |> List.iter (fun x -> printf "%d " x)
More info:
- Lists in F# (MSDN)
回答3:
Here's simple alternative that uses String.Join:
open System
let xs = [1; 2; 3; 4]
let s = "[" + String.Join("; ", xs) + "]"
printfn "%A" s