List <'T>类表示可以通过索引访问的对象的类型列表,它与数组相似,因为它可以由索引访问,但是,与数组不同,可以调整列表的大小。
创建可变列表
使用 new 关键字并调用列表的构造函数来创建列表。以下示例演示了这一点-
(* Creating a List *) open System.Collections.Generic let booksList = new List<string>() booksList.Add("Gone with the Wind") booksList.Add("Atlas Shrugged") booksList.Add("Fountainhead") booksList.Add("Thornbirds") booksList.Add("Rebecca") booksList.Add("Narnia") booksList |> Seq.iteri (fun index item -> printfn "%i: %s" index booksList.[index])
编译并执行程序时,将产生以下输出-
0: Gone with the Wind 1: Atlas Shrugged 2: Fountainhead 3: Thornbirds 4: Rebecca 5: Narnia
可变列表示例
(* Creating a List *) open System.Collections.Generic let booksList = new List<string>() booksList.Add("Gone with the Wind") booksList.Add("Atlas Shrugged") booksList.Add("Fountainhead") booksList.Add("Thornbirds") booksList.Add("Rebecca") booksList.Add("Narnia") printfn"Total %d books" booksList.Count booksList |> Seq.iteri (fun index item -> printfn "%i: %s" index booksList.[index]) booksList.Insert(2, "Roots") printfn("after inserting at index 2") printfn"Total %d books" booksList.Count booksList |> Seq.iteri (fun index item -> printfn "%i: %s" index booksList.[index]) booksList.RemoveAt(3) printfn("after removing from index 3") printfn"Total %d books" booksList.Count booksList |> Seq.iteri (fun index item -> printfn "%i: %s" index booksList.[index])
编译并执行程序时,将产生以下输出-
Total 6 books 0: Gone with the Wind 1: Atlas Shrugged 2: Fountainhead 3: Thornbirds 4: Rebecca 5: Narnia after inserting at index 2 Total 7 books 0: Gone with the Wind 1: Atlas Shrugged 2: Roots 3: Fountainhead 4: Thornbirds 5: Rebecca 6: Narnia after removing from index 3 Total 6 books 0: Gone with the Wind 1: Atlas Shrugged 2: Roots 3: Thornbirds 4: Rebecca 5: Narnia
参考链接
https://www.learnfk.com/fsharp/fsharp-mutable-lists.html
标签:index,Narnia,List,无涯,Add,booksList,Mutable,printfn,Rebecca From: https://blog.51cto.com/u_14033984/8605419