Procedura: Trovare la differenza dei set tra due elenchi (LINQ) (Visual Basic)

In questo esempio viene illustrato come usare LINQ per confrontare due elenchi di stringhe e restituire le righe presenti in names1.txt ma non in names2.txt.

Per creare i file di dati

  1. Copiare names1.txt e names2.txt nella cartella della soluzione come illustrato in Procedura: Combinare e confrontare raccolte di stringhe (LINQ) (Visual Basic).

Esempio

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  

Alcuni tipi di operazioni di query in Visual Basic, ad esempio Except, Distinct, Union e Concat, possono essere espressi solo nella sintassi basata su metodo.

Compilare il codice

Creare un progetto di applicazione console di Visual Basic con un'istruzione Imports per lo spazio dei nomi System.Linq.

Vedi anche