F#可变列表(MutableList)

F#可变列表(MutableList) 首页 / F#入门教程 / F#可变列表(MutableList)

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

技术领导力实战笔记 2022 -〔TGO 鲲鹏会〕

说透元宇宙 -〔方军〕

Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕

数据分析思维课 -〔郭炜〕

恋爱必修课 -〔李一帆〕

Java并发编程实战 -〔王宝令〕

零基础学Python -〔尹会生〕

Service Mesh实践指南 -〔周晶〕

朱赟的技术管理课 -〔朱赟〕

好记忆不如烂笔头。留下您的足迹吧 :)