MSDN 杂志
MSDN 主页 > MSDN 技术资源库 >  高级基础知识:谓词和操作
图 1 Array 和 List 提供使用谓词的方法

方法 Array List 说明
ConvertAll 将一种类型的数组或列表转换为另一种类型的数组或列表。(此方法实际上不使用 System.Predicate 委托。而是使用相似的 System.Converter 委托。)
Exists 确定所指定的数组或列表中是否含有任何与指定的谓词所定义的条件相匹配的元素。
Find 搜索与指定谓词所定义的条件相匹配的元素,并返回整个 Array 或 List 中第一个符合条件的元素。
FindAll 检索所有与指定谓词定义的条件相匹配的元素。
FindIndex   搜索与指定谓词定义的条件相匹配的元素,并返回数组中第一个以零为基础的索引。
FindLast 搜索与指定谓词定义的条件相匹配的元素,并返回整个数组或列表中最后一个符合条件的元素。
FindLastIndex   搜索与指定谓词定义的条件相匹配的元素,并返回数组中最后一个以零为基础的索引。
ForEach 对指定数组或列表中的每个元素执行指定的操作。(此方法实际上不使用 System.Predicate 委托。而是使用相似的 System.Action 委托。有关详细信息,请参阅示例。)
RemoveAll   从列表中删除所有与指定谓词定义的条件相匹配的元素。
TrueForAll 确定数组或列表中的每一个元素是否都与指定谓词定义的条件相匹配。

图 3 用文件信息填充数组实例
Private Sub RefillFileInformation()
    ' 填充 FileInfo 对象的数组和
    ' FileInfo 对象的通用 List。
    Dim di As New DirectoryInfo("C:\Windows")
    fileArray = di.GetFiles("*.*")

    fileList.Clear()
    fileList.AddRange(fileArray)

    ' 清除整个列表框的内容,然后
    ' 用找到的文件列表进行填充。
    completeListBox.Items.Clear()
    fileList.ForEach(AddressOf DisplayFullList)

    fullFileCountLabel.Text = String.Format("找到 {0} 个文件", _
        completeListBox.Items.Count)
End Sub

图 4 使用各种方法
' List 方法:
Dim exists As Boolean = fileList.Exists(match)
Dim file As FileInfo = fileList.Find(match)
Dim subList As List(Of FileInfo) = fileList.FindAll(match)
Dim file As FileInfo = fileList.FindLast(match)
fileList.RemoveAll(match)
Dim trueForAll As Boolean = fileList.TrueForAll(match)

' Array 方法:
Dim exists As Boolean = Array.Exists(fileArray, match)
Dim file As FileInfo = Array.Find(fileArray, match)
Dim subArray() As FileInfo = Array.FindAll(fileArray, match)
Dim index As Integer = Array.FindIndex(fileArray, match)
Dim file As FileInfo = Array.FindLast(fileArray, match)
Dim index As Integer = Array.FindLastIndex(fileArray, match)
Dim trueForAll As Boolean = Array.TrueForAll(fileArray, match)

 

© 2006 Microsoft Corporation 版权所有。保留所有权利。使用规定。