VB.net中,List有什么方法与属性
在VB.NET中,List 通常指的是 List<T> 泛型集合,它是定义在 System.Collections.Generic 命名空间下的一个动态数组,允许你在运行时添加、删除和搜索元素。T 是一个占位符,代表你可以存储在列表中的任何类型的对象。 |
---|
以下是 List<T> 的一些常用方法和属性,以及如何使用它们的例子:
属性
Count:获取列表中元素的数量。
Dim myList As New List(Of String)
myList.Add("Apple")
myList.Add("Banana")
myList.Add("Cherry")
Console.WriteLine(myList.Count) ' 输出 3
Capacity:获取或设置列表能够包含的元素的数量。当添加元素时,如果当前容量不足以容纳新元素,列表的容量将自动增加。
Dim myList As New List(Of Integer)
Console.WriteLine(myList.Capacity) ' 初始容量,可能是默认值,如4
myList.Add(1)
myList.Add(2)
Console.WriteLine(myList.Capacity)
'
方法
1.Add(item):在列表的末尾添加一个元素。
'vbnet
Dim myList As New List(Of String)
myList.Add("Hello") ' 添加元素 "Hello"
AddRange(collection):在列表的末尾添加指定集合的所有元素。
'vbnet
Dim myList As New List(Of Integer)
Dim numbers As New List(Of Integer) {1, 2, 3}
myList.AddRange(numbers) ' 添加集合 numbers 中的所有元素
2.Clear():移除列表中的所有元素。
Dim myList As New List(Of String)
myList.Add("One")
myList.Add("Two")
myList.Clear() ' 现在列表是空的
3.Contains(item):确定列表中是否包含特定元素。
Dim myList As New List(Of String)
myList.Add("Apple")
If myList.Contains("Apple") Then
Console.WriteLine("Apple is in the list.")
End If
4.IndexOf(item):返回列表中第一个匹配项的索引,如果列表不包含该元素,则返回 -1。
Dim myList As New List(Of String)
myList.Add("Apple")
myList.Add("Banana")
Dim index As Integer = myList.IndexOf("Banana") ' index 将会是 1
5.Insert(index, item):在列表的指定位置插入一个元素。
Dim myList As New List(Of String)
myList.Add("Apple")
myList.Insert(1, "Banana") ' 在索引 1 的位置插入 "Banana"
6.Remove(item):从列表中移除第一个匹配项。
Dim myList As New List(Of String)
myList.Add("Apple")
myList.Add("Banana")
myList.Remove("Banana") ' 移除 "Banana"
7.RemoveAll(match):移除列表中所有匹配指定条件的元素。
vbnet
Dim myList As New List(Of String)
myList.Add("Apple")
myList.Add("Banana")
myList.Add("Cherry")
myList.RemoveAll(Function(item) item.StartsWith("A"))
' 移除所有以 "A" 开头的元素
8.RemoveAt(index):通过指定索引移除列表中的一个元素。
Dim myList As New List(Of String)
myList.Add("Apple")
myList.Add("Banana")
myList.RemoveAt(0) ' 移除索引 0 的元素,即 "Apple"
以上列举的方法和属性只是 List<T> 的一部分。
List<T> 提供了丰富的功能来操作集合,
包括排序、搜索和修改元素等。