Sdílet prostřednictvím


Postupy: Hledání množinových rozdílů mezi dvěma seznamy (LINQ)

Tento příklad ukazuje použití LINQ porovnání dvou seznamů řetězců a výstupní řádků, které jsou names1.txt, ale ne v names2.txt.

Vytvoření datové soubory

Příklad

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
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 in debug mode.
        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
     */

Některé typy operací dotazu v obou C# a Visual Basic, jako například Except``1, Distinct``1, Union``1, a Concat``1, lze vyjádřit pouze v syntaxi metoda založena.

Probíhá kompilace kódu

  • Vytvoření Visual Studio projektu, který se zaměřuje .NET Framework verze 3.5.Ve výchozím nastavení projektu odkazuje na System.Core.dll a using směrnice (C#) nebo Imports prohlášení (Visual Basic) pro obor názvů System.Linq.V jazyce C# projekty, přidejte using směrnice pro obor názvů System.IO.

  • Zkopírujte tento kód do projektu.

  • Stisknutím klávesy F5 sestavit a spustit program.

  • Stisknutím libovolné klávesy uzavřete okno konzoly.

Viz také

Koncepty

LINQ a řetězce