Aracılığıyla paylaş


Nasıl yapılır: İki Liste Arasında Ayarlanmış Farkı Bulma (LINQ)

Bu örnek, nasıl kullanılacağını gösterir LINQ iki liste dizeleri karşılaştırmak ve names1.txt de var, ancak names2.txt Bu satırlar çıkış.

Veri dosyaları oluşturmak için

Örnek

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

Sorgu işlemleri her iki C# [NULL]'taki bazı türleri ve Visual Basic, gibi Except``1, Distinct``1, Union``1, ve Concat``1, yöntem temelli sözdizimine yalnızca ifade edilebilir.

Kod Derleniyor

  • Oluşturma bir Visual Studio hedefleyen proje .NET Framework sürüm 3.5.Varsayılan olarak, proje başvuru System.Core.dll sahiptir ve bir using yönergesi (C#) veya Imports deyimi (Visual Basic) System.Linq ad alanı.C# projeleri, ekleme bir using yönergesi System.IO ad alanı.

  • Projenize bu kodu kopyalayın.

  • Derlemek ve program çalıştırmak için F5 tuşuna basın.

  • Konsol penceresine çıkmak için herhangi bir tuşa basın.

Ayrıca bkz.

Kavramlar

LINQ ve Dizeler