共用方式為


HOW TO:執行左外部聯結 (C# 程式設計手冊)

左外部聯結是傳回第一個集合之每個項目的聯結,無論在第二個集合中有無相關項目都一樣。 您可以使用 LINQ 執行左外部聯結,方法是在群組聯結的結果上呼叫 DefaultIfEmpty

範例

下列範例示範如何在群組聯結的結果上使用 DefaultIfEmpty 方法,以執行左外部聯結。

產生兩個集合之左外部聯結的第一個步驟是使用群組聯結執行內部聯結 (如需此處理序的說明,請參閱 HOW TO:執行內部聯結 (C# 程式設計手冊))。在此範例中,Person 物件的清單是根據符合 Pet.Owner 的 Person 物件,內部聯結至 Pet 物件的清單。

第二個步驟是包含結果集中第一個 (左) 集合中的每個項目,即使該項目在右集合中沒有相符項目也一樣。 這個動作可以藉由從群組聯結在相符項目的每個序列上呼叫 DefaultIfEmpty 而達成。 在此範例中,DefaultIfEmpty 是在每個相符 Pet 物件的序列上叫用。 如果任何 Person 物件之相符 Pet 物件的序列是空的,則傳回包含單一、預設值的集合,因此可以確定能夠在結果集合中表示每個 Person 物件。

注意事項注意事項

參考型別的預設值是 null,因此範例會在存取每個 Pet 集合的每個項目之前檢查 Null 參考。

        class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }

        class Pet
        {
            public string Name { get; set; }
            public Person Owner { get; set; }
        }

        public static void LeftOuterJoinExample()
        {
            Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
            Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
            Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
            Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };

            Pet barley = new Pet { Name = "Barley", Owner = terry };
            Pet boots = new Pet { Name = "Boots", Owner = terry };
            Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
            Pet bluemoon = new Pet { Name = "Blue Moon", Owner = terry };
            Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

            // Create two lists.
            List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
            List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };

            var query = from person in people
                        join pet in pets on person equals pet.Owner into gj
                        from subpet in gj.DefaultIfEmpty()
                        select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };

            foreach (var v in query)
            {
                Console.WriteLine("{0,-15}{1}", v.FirstName + ":", v.PetName);
            }
        }

        // This code produces the following output:
        //
        // Magnus:         Daisy
        // Terry:          Barley
        // Terry:          Boots
        // Terry:          Blue Moon
        // Charlotte:      Whiskers
        // Arlene:

編譯程式碼

  • 在 Visual Studio 中建立一個新的主控台應用程式。

  • 將參考加入至 System.Core.dll (如果尚未參考)。

  • 包括 System.Linq 命名空間。

  • 從範例複製程式碼,並將其貼入 program.cs 檔中 Main 方法的下方。 將一行程式碼加入至 Main 方法,以呼叫您所貼上的方法。

  • 執行程式。

請參閱

工作

HOW TO:執行內部聯結 (C# 程式設計手冊)

HOW TO:執行群組聯結 (C# 程式設計手冊)

參考

Join

GroupJoin

匿名型別 (C# 程式設計手冊)

概念

聯結作業

匿名型別 (Visual Basic)