通过


如何:确定两个列表之间的集合差异(LINQ)(Visual Basic)

此示例演示如何使用 LINQ 比较两个字符串列表,并输出 names1.txt 但不在 names2.txt中的行。

创建数据文件

  1. 将 names1.txt 和 names2.txt 复制到解决方案文件夹,如 How to: Combine and Compare String Collections (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 中的某些类型的查询作(例如ExceptDistinctUnionConcat)只能以基于方法的语法表示。

编译代码

创建 Visual Basic 控制台应用程序项目,其中包含 Imports System.Linq 命名空间的语句。

另请参阅