How to find the set difference between two lists (LINQ) (C#)

This example shows how to use LINQ to compare two lists of strings and output those lines that are in names1.txt but not in names2.txt.

To create the data files

  1. Copy names1.txt and names2.txt to your solution folder as shown in How to combine and compare string collections (LINQ) (C#).

Example

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  
     */  

Some types of query operations in C#, such as Except, Distinct, Union, and Concat, can only be expressed in method-based syntax.

Compiling the Code

Create a C# console application project, with using directives for the System.Linq and System.IO namespaces.