如何:尋找兩個清單之間的集合差異 (LINQ) (Visual Basic)

此範例示範如何使用 LINQ 來比較兩個字串清單,並輸出 names1.txt 中但未在 names2.txt中的行。

建立數據檔

  1. 將 names1.txt 和 names2.txt 複製到您的方案資料夾,如 如何:合併和比較字串集合 (LINQ) (Visual Basic) 所示。

範例

Class CompareLists

    Shared Sub Main()

        ' Create the IEnumerable data sources.
        Dim names1 As String() = System.IO.File.ReadAllLines("../../../names1.txt")
        Dim names2 As String() = System.IO.File.ReadAllLines("../../../names2.txt")

        ' Create the query. Note that method syntax must be used here.
        Dim differenceQuery = names1.Except(names2)
        Console.WriteLine("The following lines are in names1.txt but not names2.txt")

        ' Execute the query.
        For Each name As String In differenceQuery
            Console.WriteLine(name)
        Next

        ' Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()
    End Sub
End Class
' Output:
' The following lines are in names1.txt but not names2.txt
' Potra, Cristina
' Noriega, Fabricio
' Aw, Kam Foo
' Toyoshima, Tim
' Guy, Wey Yuan
' Garcia, Debra

Visual Basic 中的某些查詢作業類型,例如 Except、 Distinct、 Union和 Concat,只能以方法為基礎的語法來表示。

編譯程式碼

建立一個包含 Imports 語句以使用 System.Linq 命名空間的 Visual Basic 控制台應用程式專案。

另請參閱