如何查找两个列表之间的差集 (LINQ) (Visual Basic)

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

创建数据文件

  1. 按照如何合并和比较字符串集合 (LINQ) (Visual Basic) 中的说明,将 names1.txt 和 names2.txt 复制到解决方案文件夹中。

示例

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 控制台应用程序项目,其中包含用于 System.Linq 命名空间的 Imports 语句。

另请参阅