次の方法で共有


方法: 拡張子でファイルをグループ化する (LINQ) (Visual Basic)

この例では、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 などの他のコンテキストでは、このようなキャッシュは必要ありません。

コードをコンパイルする

System.Linq 名前空間の Imports ステートメントを使用して、Visual Basic コンソール アプリケーション プロジェクトを作成します。

こちらも参照ください