Compartilhar via


Como: Encontrar a diferença de conjunto entre duas listas (LINQ)

Este exemplo mostra como usar LINQ para comparar duas listas de seqüências de caracteres e a saída dessas linhas que estão em names1.txt, mas não em names2.txt.

Para criar os arquivos de dados

Exemplo

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

Alguns tipos de operações de consulta em ambos os C# e Visual Basic, como Except, Distinct, Union, e Concat<TSource>, que só pode ser expresso na sintaxe baseada em método.

Compilando o código

  • Criar um Visual Studio o projeto que se destina a .NET Framework versão 3.5. Por padrão, o projeto tem uma referência a System.Core.dll e um using diretiva (C#) ou Imports instrução (Visual Basic) para o namespace System. LINQ. No C# projetos, adicione um using a diretiva para o namespace System. IO.

  • Copie este código em seu projeto.

  • Pressione F5 para compilar e executar o programa.

  • Pressione qualquer tecla para sair da janela do console.

Consulte também

Conceitos

LINQ e seqüências de caracteres