Come trovare la differenza di set tra due elenchi (LINQ) (C#)

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 Come combinare e confrontare raccolte di stringhe (LINQ) (C#).

Esempio

class CompareLists  
{
    static void Main()  
    {  
        // Create the IEnumerable data sources.  
        string[] names1 = System.IO.File.ReadAllLines(@"../../../names1.txt");  
        string[] names2 = System.IO.File.ReadAllLines(@"../../../names2.txt");  
  
        // Create the query. Note that method syntax must be used here.  
        IEnumerable<string> differenceQuery =  
          names1.Except(names2);  
  
        // Execute the query.  
        Console.WriteLine("The following lines are in names1.txt but not names2.txt");  
        foreach (string s in differenceQuery)  
            Console.WriteLine(s);  
  
        // Keep the console window open until the user presses a key.
        Console.WriteLine("Press any key to exit");  
        Console.ReadKey();  
    }  
}  
/* 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 C#, ad esempio Except, Distinct, Union e Concat, possono essere espressi solo nella sintassi basata su metodo.

Compilazione del codice

Creare un progetto di applicazione console C# con direttive using per gli spazi dei nomi System.Linq e System.IO.