此範例示範如何使用 LINQ,在檔案或資料夾清單上執行進階群組和排序作業。 它也會示範如何使用 Skip 和 Take 方法,在控制台視窗中分頁輸出。
範例
下列查詢示範如何依擴展名將指定目錄樹狀目錄的內容分組。
Module GroupByExtension
Public Sub Main()
' Root folder to query, along with all subfolders.
Dim startFolder As String = "C:\program files\Microsoft Visual Studio 9.0\VB\"
' Used in WriteLine() to skip over startfolder in output lines.
Dim rootLength As Integer = startFolder.Length
'Take a snapshot of the folder contents
Dim dir As New System.IO.DirectoryInfo(startFolder)
Dim fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories)
' Create the query.
Dim queryGroupByExt = From file In fileList _
Group By file.Extension.ToLower() Into fileGroup = Group _
Order By ToLower _
Select fileGroup
' Execute the query. By storing the result we can
' page the display with good performance.
Dim groupByExtList = queryGroupByExt.ToList()
' Display one group at a time. If the number of
' entries is greater than the number of lines
' in the console window, then page the output.
Dim trimLength = startFolder.Length
PageOutput(groupByExtList, trimLength)
End Sub
' Pages console display for large query results. No more than one group per page.
' This sub specifically works with group queries of FileInfo objects
' but can be modified for any type.
Sub PageOutput(ByVal groupQuery, ByVal charsToSkip)
' "3" = 1 line for extension key + 1 for "Press any key" + 1 for input cursor.
Dim numLines As Integer = Console.WindowHeight - 3
' Flag to indicate whether there are more results to display
Dim goAgain As Boolean = True
For Each fg As IEnumerable(Of System.IO.FileInfo) In groupQuery
' Start a new extension at the top of a page.
Dim currentLine As Integer = 0
Do While (currentLine < fg.Count())
Console.Clear()
Console.WriteLine(fg(0).Extension)
' Get the next page of results
' No more than one filename per page
Dim resultPage = From file In fg _
Skip currentLine Take numLines
' Execute the query. Trim the display output.
For Each line In resultPage
Console.WriteLine(vbTab & line.FullName.Substring(charsToSkip))
Next
' Advance the current position
currentLine = numLines + currentLine
' Give the user a chance to break out of the loop
Console.WriteLine("Press any key for next page or the 'End' key to exit.")
Dim key As ConsoleKey = Console.ReadKey().Key
If key = ConsoleKey.End Then
goAgain = False
Exit For
End If
Loop
Next
End Sub
End Module
此程序的輸出可能很長,這取決於本機文件系統的詳細資訊,以及 startFolder 的設定值。 若要啟用檢視所有結果,此範例示範如何逐頁檢視結果。 相同的技術可以套用至 Windows 和 Web 應用程式。 請注意,由於代碼會對群組中的項目進行分頁,因此需要使用巢狀 For Each 迴圈。 另外還有一些額外的邏輯可計算清單中的目前位置,並讓使用者停止分頁並結束程式。 在此特定情況下,分頁查詢會在原始查詢的快取結果上執行。 在其他情境中,例如 LINQ to SQL,此類快取是不需要的。
編譯程式碼
建立一個包含 Imports 語句以使用 System.Linq 命名空間的 Visual Basic 控制台應用程式專案。