Aracılığıyla paylaş


Nasıl yapılır: iç birleşimler (C# Programlama Kılavuzu) gerçekleştirmek

İlişkisel veritabanı bakımından bir INNER JOIN hangi her öğe ilk koleksiyon, sonuç kümesinde görüntülenir ikinci koleksiyonundaki eşleşen her öğe için bir kez üretir.İlk koleksiyondaki öğe eşleşen bir öğe varsa, sonuç kümesinde görünmez.Join Tarafından çağrılan yöntemi, join C# ' ta yan bir iç birleşim uygular.

Bu konuda bir iç birleşim dört çeşidi gerçekleştirmek gösterilmiştir:

  • İki veri kaynaklarından basit bir anahtarı temel öğeleri belirtilirler basit bir iç birleşim.

  • Öğeleri iki veri kaynaklarından belirtilirler bir iç birleşim esas alan bir Bileşik anahtarı.Birden fazla değeri oluşan bir anahtar bir bileşik anahtar, birden fazla özelliğini temel alan öğeleri ilişkilendirmek sağlar.

  • A birden fazla birleşim hangi art arda birleştirme işlemleri birbirine eklenir.

  • Bir dış birleşim bir grup birleştirme kullanılarak gerçekleştirilir.

Örnek

Basit anahtar birleşim örneği

Aşağıdaki örnek, iki kullanıcı tanımlı türler, nesneleri içeren iki koleksiyonlar oluşturur Person ve Pet.Sorgu kullanır join yan tümcesinde eşleşecek şekilde C# Person ile nesneleri Pet whose nesneleri Owner olan Person.select C# [NULL]'ta yan tümcesi sonuç nesneleri nasıl görüneceğini tanımlar.Bu örnekte, sonuçta elde edilen nesneler sahibinin adı ve Evcil hayvanınızın adı anonim türleri şunlardır.

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

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

        /// <summary>
        /// Simple inner join.
        /// </summary>
        public static void InnerJoinExample()
        {
            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" };
            Person rui = new Person { FirstName = "Rui", LastName = "Raposo" };

            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 = rui };
            Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

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

            // Create a collection of person-pet pairs. Each element in the collection
            // is an anonymous type containing both the person's name and their pet's name.
            var query = from person in people
                        join pet in pets on person equals pet.Owner
                        select new { OwnerName = person.FirstName, PetName = pet.Name };

            foreach (var ownerAndPet in query)
            {
                Console.WriteLine("\"{0}\" is owned by {1}", ownerAndPet.PetName, ownerAndPet.OwnerName);
            }
        }

        // This code produces the following output:
        //
        // "Daisy" is owned by Magnus
        // "Barley" is owned by Terry
        // "Boots" is owned by Terry
        // "Whiskers" is owned by Charlotte
        // "Blue Moon" is owned by Rui

Dikkat Person whose nesne LastName "Huff" yoktur çünkü sonuçta görünmez olan hiçbir Pet olan nesne Pet.Owner eşit Person.

Bileşik anahtar birleşim örneği

Öğeleri tek bir özelliğe dayalı birleştiriliyor yerine bir bileşik anahtar öğeleri birden çok özelliğe göre karşılaştırmak için kullanabilirsiniz.Bunu yapmak için her koleksiyon özelliklerini karşılaştırmak istediğiniz oluşan bir anonim tür dönmek için anahtar Seçici işlevi belirtin.Özellikler etiketlerseniz, bunlar her anahtarın anonim yazıyla aynı etiketi olması gerekir.Özellikleri de aynı sırada yer almalıdır.

Aşağıdaki örnek bir listesini kullanır Employee nesneleri ve bir listesini Student hangi çalışanların da öğrenciler olduğunu belirlemek için nesneler.Hem de bu tür bir FirstName ve bir LastName türünde özellik String.Her listenin öğelerden birleştirme anahtarları oluşturma işlevleri oluşan bir anonim tür dönmek FirstName ve LastName her öğenin özellikleri.Birleştirme işlemi eşitlik bileşik bu tuşları karşılaştırır ve burada hem ilk ad ve soyad eşleşen çiftleri nesnelerinin her listeden döndürür.

        class Employee
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int EmployeeID { get; set; }
        }

        class Student
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int StudentID { get; set; }
        }

        /// <summary>
        /// Performs a join operation using a composite key.
        /// </summary>
        public static void CompositeKeyJoinExample()
        {
            // Create a list of employees.
            List<Employee> employees = new List<Employee> {
                new Employee { FirstName = "Terry", LastName = "Adams", EmployeeID = 522459 },
                 new Employee { FirstName = "Charlotte", LastName = "Weiss", EmployeeID = 204467 },
                 new Employee { FirstName = "Magnus", LastName = "Hedland", EmployeeID = 866200 },
                 new Employee { FirstName = "Vernette", LastName = "Price", EmployeeID = 437139 } };

            // Create a list of students.
            List<Student> students = new List<Student> {
                new Student { FirstName = "Vernette", LastName = "Price", StudentID = 9562 },
                new Student { FirstName = "Terry", LastName = "Earls", StudentID = 9870 },
                new Student { FirstName = "Terry", LastName = "Adams", StudentID = 9913 } };

            // Join the two data sources based on a composite key consisting of first and last name,
            // to determine which employees are also students.
            IEnumerable<string> query = from employee in employees
                                        join student in students
                                        on new { employee.FirstName, employee.LastName }
                                        equals new { student.FirstName, student.LastName }
                                        select employee.FirstName + " " + employee.LastName;

            Console.WriteLine("The following people are both employees and students:");
            foreach (string name in query)
                Console.WriteLine(name);
        }

        // This code produces the following output:
        //
        // The following people are both employees and students:
        // Terry Adams
        // Vernette Price

Birden fazla birleşim örneği

Birleştirme işlemi herhangi bir sayıda birbirlerine birden çok birleştirme gerçekleştirmek için eklenebilir.Her join C# [NULL]'ta yan tümcesi belirtilen veri kaynağı önceki birleştirme sonuçlarını belirtilirler.

Aşağıdaki örnek, üç koleksiyonlar oluşturur: listesini Person nesneleri, bir listesini Cat nesneleri ve bir listesini Dog nesneler.

İlk join C# [NULL]'ta yan tümcesi eşleşen kişiler ve kediler dayalı bir Person nesne eşleştirme Cat.Owner.İçeren anonim türleri dizisi döndürür Person nesnesi ve Cat.Name.

İkinci join C# [NULL]'ta yan tümcesi ile ilk birleşim tarafından döndürülen Adsız türleri belirtilirler Dog köpekler, sağlanan listesi nesneleri bağlı oluşan bir bileşik anahtar Owner türünde özellik Person, hayvan'ın adının ilk harfi.İçeren anonim türleri dizisi döndürür Cat.Name ve Dog.Name her bir eşleşen çifti özelliklerinden.Bu bir iç birleşim olduğundan, yalnızca bir eşleşme ikinci veri kaynağına sahip ilk veri kaynağı nesnelerden döndürülür.

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

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

        class Cat : Pet
        { }

        class Dog : Pet
        { }

        public static void MultipleJoinExample()
        {
            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" };
            Person rui = new Person { FirstName = "Rui", LastName = "Raposo" };
            Person phyllis = new Person { FirstName = "Phyllis", LastName = "Harris" };

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

            Dog fourwheeldrive = new Dog { Name = "Four Wheel Drive", Owner = phyllis };
            Dog duke = new Dog { Name = "Duke", Owner = magnus };
            Dog denim = new Dog { Name = "Denim", Owner = terry };
            Dog wiley = new Dog { Name = "Wiley", Owner = charlotte };
            Dog snoopy = new Dog { Name = "Snoopy", Owner = rui };
            Dog snickers = new Dog { Name = "Snickers", Owner = arlene };

            // Create three lists.
            List<Person> people =
                new List<Person> { magnus, terry, charlotte, arlene, rui, phyllis };
            List<Cat> cats =
                new List<Cat> { barley, boots, whiskers, bluemoon, daisy };
            List<Dog> dogs =
                new List<Dog> { fourwheeldrive, duke, denim, wiley, snoopy, snickers };

            // The first join matches Person and Cat.Owner from the list of people and
            // cats, based on a common Person. The second join matches dogs whose names start
            // with the same letter as the cats that have the same owner.
            var query = from person in people
                        join cat in cats on person equals cat.Owner
                        join dog in dogs on 
                        new { Owner = person, Letter = cat.Name.Substring(0, 1) }
                        equals new { dog.Owner, Letter = dog.Name.Substring(0, 1) }
                        select new { CatName = cat.Name, DogName = dog.Name };

            foreach (var obj in query)
            {
                Console.WriteLine(
                    "The cat \"{0}\" shares a house, and the first letter of their name, with \"{1}\".", 
                    obj.CatName, obj.DogName);
            }
        }

        // This code produces the following output:
        //
        // The cat "Daisy" shares a house, and the first letter of their name, with "Duke".
        // The cat "Whiskers" shares a house, and the first letter of their name, with "Wiley".

Gruplandırılmış katılmak örnek kullanarak iç birleşim

Aşağıdaki örnek bir iç birleşim grubu birleştirme kullanarak uygulamak nasıl gösterir.

De query1, listesini Person nesneleri listesine grup katılmış Pet nesneleri temel Person eşleşen Pet.Owner özelliği.Ara gruplar, burada her grup oluşur topluluğu Grup birleşim oluşturur bir Person nesnesi ve eşleşen bir sıra Pet nesneler.

İkinci ekleyerek from bu Sırası sıralarının sorgu yan tümcesini birleştirilmiş (veya düzleştirilmiş) daha uzun bir sýraya.Son sıra öðelerinin türü tarafından belirtilen select yan tümcesi.Bu örnekte, oluşan anonim bir türü olduğunu Person.FirstName ve Pet.Name her bir eşleşen çifti için özellikleri.

Sonucu query1 kullanarak alınmış sonuç kümesine eşittir join yan tümcesi olmadan into bir iç birleşim gerçekleştirmek için yan tümcesi.query2 Eşdeğer bu sorgu değişkeni gösterir.

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

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

        /// <summary>
        /// Performs an inner join by using GroupJoin().
        /// </summary>
        public static void InnerGroupJoinExample()
        {
            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 query1 = from person in people
                         join pet in pets on person equals pet.Owner into gj
                         from subpet in gj
                         select new { OwnerName = person.FirstName, PetName = subpet.Name };

            Console.WriteLine("Inner join using GroupJoin():");
            foreach (var v in query1)
            {
                Console.WriteLine("{0} - {1}", v.OwnerName, v.PetName);
            }

            var query2 = from person in people
                         join pet in pets on person equals pet.Owner
                         select new { OwnerName = person.FirstName, PetName = pet.Name };

            Console.WriteLine("\nThe equivalent operation using Join():");
            foreach (var v in query2)
                Console.WriteLine("{0} - {1}", v.OwnerName, v.PetName);
        }

        // This code produces the following output:
        //
        // Inner join using GroupJoin():
        // Magnus - Daisy
        // Terry - Barley
        // Terry - Boots
        // Terry - Blue Moon
        // Charlotte - Whiskers
        //
        // The equivalent operation using Join():
        // Magnus - Daisy
        // Terry - Barley
        // Terry - Boots
        // Terry - Blue Moon
        // Charlotte - Whiskers

Kod Derleniyor

  • Yeni bir konsol uygulaması proje oluşturmak Visual Studio.

  • Zaten başvurulmayan System.Core.dll bir başvuru ekleyin.

  • Dahil System.Linq ad.

  • Kopyalayıp altındaki program.cs dosyasına örnek kodu yapıştırın Main yöntemi.Bir kod satırını ekleyin Main , yapıştırdığınız yöntemini çağırmak için yöntem.

  • Programı çalıştırın.

Ayrıca bkz.

Görevler

Nasıl yapılır: gruplanmış birleşimler (C# Programlama Kılavuzu) gerçekleştirmek

Nasıl yapılır: sol dış birleşimler (C# Programlama Kılavuzu) gerçekleştirmek

How to: Join Two Collections (C#) LINQ to XML

Başvuru

Join

GroupJoin

Anonim türleri (C# Programlama Kılavuzu)

Kavramlar

Birleşim işlemleri

Anonim türleri (Visual Basic)