共用方式為


HOW TO:尋找兩個清單之間的差異 (LINQ)

這個範例顯示如何使用 LINQ 比較兩份字串清單,然後輸出在 names1.txt 但不在 names2.txt 中的字串行。

若要建立資料檔

範例

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

C# 和 Visual Basic 中的部分查詢作業類型 (如 ExceptDistinctUnionConcat<TSource>) 只能以方法架構的語法表示。

編譯程式碼

  • 建立一個以 .NET Framework 3.5 版為目標的 Visual Studio 專案。 專案預設會含 System.Core.dll 的參考,以及 System.Linq 命名空間 (Namespace) 的 using 指示詞 (C#) 或 Imports 陳述式 (Visual Basic)。 請在 C# 專案中,加入 System.IO 命名空間的 using 指示詞。

  • 將此程式碼複製至您的專案。

  • 按 F5 編譯和執行程式。

  • 按任何鍵離開主控台視窗。

請參閱

概念

LINQ 和字串