Aracılığıyla paylaş


Nasıl yapılır: özel birleştirme (C# Programlama Kılavuzu) işlemleri

Bu örnek ile mümkün olmayan birleştirme işlemlerini gerçekleştirmek gösterilmiştir join yan tümcesi.Bir sorgu ifadesinde join yan tümcesi sınırlı ve birleştirme işlemi için en iyi duruma getirilmiş, yanı sıra yaygın equijoins yazın.Equijoin gerçekleştirirken, büyük olasılıkla her zaman en iyi performansı kullanarak elde edersiniz join yan tümcesi.

Ancak, join yan tümcesi aşağıdaki durumlarda kullanılamaz:

  • Ne zaman birleştirme eşitsizlik (bir olmayan-equijoin) bir deyim predicated.

  • Ne zaman birleştirme eşitlik ya da eşitsizlik birden çok deyim predicated.

  • Ne zaman birleştirme işleminden önce sağ tarafı (iç) sırası için geçici aralık değişkeni tanıtmak vardır.

Equijoins olmayan birleşimler gerçekleştirmek için birden fazla kullanabilirsiniz from her veri kaynağı bağımsız olarak tanıtmak için yan tümceleri.Sonra bir doðrulama deyimi içinde geçerli bir where her kaynak aralığı değişkenine yan tümcesi.İfade bir yöntem çağrısı şeklinde de alabilir.

[!NOT]

Bu tür bir özel birleştirme işlemi çok kullanımı ile karıştırmayın from iç koleksiyonlarını erişmek için yan tümceleri.Daha fazla bilgi için bkz. JOIN yan tümcesi (C# Reference).

Örnek

Aşağıdaki örnekte ilk yöntem, basit bir çapraz birleşim gösterir.Çok büyük boyutlu sonuç kümeleri üretebilir çünkü çapraz birleştirmeler dikkatli kullanılmalıdır.Ancak, bunlar karşısında ek sorgular çalıştırmak kaynak dizileri oluştururken bazı senaryolarda yararlı olabilir.

İkinci yöntem, category ID sol taraftaki kategori listesinde listelenen tüm ürünler dizisini üretir.Kullanımına dikkat edin let yan tümcesi ve Contains geçici bir dizi oluşturmak için yöntem.Dizi önce sorgu oluşturmak ve ilk ortadan kaldırmak mümkündür from yan tümcesi.

     class CustomJoins
     {

         #region Data

         class Product
         {
             public string Name { get; set; }
             public int CategoryID { get; set; }
         }

         class Category
         {
             public string Name { get; set; }
             public int ID { get; set; }
         }

         // Specify the first data source.
         List<Category> categories = new List<Category>()
 { 
     new Category(){Name="Beverages", ID=001},
     new Category(){ Name="Condiments", ID=002},
     new Category(){ Name="Vegetables", ID=003},         
 };

         // Specify the second data source.
         List<Product> products = new List<Product>()
{
   new Product{Name="Tea",  CategoryID=001},
   new Product{Name="Mustard", CategoryID=002},
   new Product{Name="Pickles", CategoryID=002},
   new Product{Name="Carrots", CategoryID=003},
   new Product{Name="Bok Choy", CategoryID=003},
   new Product{Name="Peaches", CategoryID=005},
   new Product{Name="Melons", CategoryID=005},
   new Product{Name="Ice Cream", CategoryID=007},
   new Product{Name="Mackerel", CategoryID=012},
 };
         #endregion

         static void Main()
         {
             CustomJoins app = new CustomJoins();
             app.CrossJoin();
             app.NonEquijoin();

             Console.WriteLine("Press any key to exit.");
             Console.ReadKey();
         }

         void CrossJoin()
         {
             var crossJoinQuery =
                 from c in categories
                 from p in products
                 select new { c.ID, p.Name };

             Console.WriteLine("Cross Join Query:");
             foreach (var v in crossJoinQuery)
             {
                 Console.WriteLine("{0,-5}{1}", v.ID, v.Name);
             }
         }

         void NonEquijoin()
         {
             var nonEquijoinQuery =
                 from p in products
                 let catIds = from c in categories
                              select c.ID
                 where catIds.Contains(p.CategoryID) == true
                 select new { Product = p.Name, CategoryID = p.CategoryID };

             Console.WriteLine("Non-equijoin query:");
             foreach (var v in nonEquijoinQuery)
             {
                 Console.WriteLine("{0,-5}{1}", v.CategoryID, v.Product);
             }
         }
     }
     /* Output:
 Cross Join Query:
 1    Tea
 1    Mustard
 1    Pickles
 1    Carrots
 1    Bok Choy
 1    Peaches
 1    Melons
 1    Ice Cream
 1    Mackerel
 2    Tea
 2    Mustard
 2    Pickles
 2    Carrots
 2    Bok Choy
 2    Peaches
 2    Melons
 2    Ice Cream
 2    Mackerel
 3    Tea
 3    Mustard
 3    Pickles
 3    Carrots
 3    Bok Choy
 3    Peaches
 3    Melons
 3    Ice Cream
 3    Mackerel
 Non-equijoin query:
 1    Tea
 2    Mustard
 2    Pickles
 3    Carrots
 3    Bok Choy
 Press any key to exit.
      */

Aşağıdaki örnekte, sorgu JOIN yan tümcesi önce kendi iç (sağ tarafta) sırası alınamıyor, anahtarları eşleşen üzerinde temel alan iki sıraları birleştirmelisiniz.Bu birleşim ile gerçekleştirilen, bir join yan tümcesi, sonra Split yöntemi her öğe için çağrılacak sahip.Kullanımı çok from yan tümcelerini sorgu yinelenen yöntemi çağrısının giderlerinden kaçınmak etkinleştirir.Ancak, bu yana join bu özel durumda, yine de olabilir kullanarak çok daha hızlı optimize from yan tümceleri.Sonuçları öncelikle nasıl pahalı yöntem çağrısı olduğuna bağlı olarak değişir.

class MergeTwoCSVFiles
{
    static void Main()
    {
        // See section Compiling the Code for information about the data files.
        string[] names = System.IO.File.ReadAllLines(@"../../../names.csv");
        string[] scores = System.IO.File.ReadAllLines(@"../../../scores.csv");

        // Merge the data sources using a named type.
        // You could use var instead of an explicit type for the query.
        IEnumerable<Student> queryNamesScores =
            // Split each line in the data files into an array of strings.
            from name in names
            let x = name.Split(',')
            from score in scores
            let s = score.Split(',')
            // Look for matching IDs from the two data files.
            where x[2] == s[0]
            // If the IDs match, build a Student object.
            select new Student()
            {
                FirstName = x[0],
                LastName = x[1],
                ID = Convert.ToInt32(x[2]),
                ExamScores = (from scoreAsText in s.Skip(1)
                              select Convert.ToInt32(scoreAsText)).
                              ToList()
            };

        // Optional. Store the newly created student objects in memory
        // for faster access in future queries
        List<Student> students = queryNamesScores.ToList();

        foreach (var student in students)
        {
            Console.WriteLine("The average score of {0} {1} is {2}.",
                student.FirstName, student.LastName, student.ExamScores.Average());
        }

        //Keep console window open in debug mode
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }
    public List<int> ExamScores { get; set; }
}

/* Output: 
    The average score of Omelchenko Svetlana is 82.5.
    The average score of O'Donnell Claire is 72.25.
    The average score of Mortensen Sven is 84.5.
    The average score of Garcia Cesar is 88.25.
    The average score of Garcia Debra is 67.
    The average score of Fakhouri Fadi is 92.25.
    The average score of Feng Hanying is 88.
    The average score of Garcia Hugo is 85.75.
    The average score of Tucker Lance is 81.75.
    The average score of Adams Terry is 85.25.
    The average score of Zabokritski Eugene is 83.
    The average score of Tucker Michael is 92.
 */

Kod Derleniyor

  • Oluşturma bir Visual Studio hedefler konsol uygulaması projesi .NET Framework 3.5 veya sonraki bir sürümü.Varsayılan olarak, proje başvuru System.Core.dll sahiptir ve bir using System.Linq ad alanı için yönerge.

  • Yerine Program önceki örnekteki kodu ile sınıf.

  • ' Teki yönergeleri Nasıl yapılır: (LINQ) benzer dosyaların içeriğini birleştirme veri dosyaları, scores.csv ve names.csv ayarlamak için.

  • 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.

Görevler

Nasıl yapılır: birleştirme yan tümcesi (C# Programlama Kılavuzu) sonuçları

Başvuru

JOIN yan tümcesi (C# Reference)

Kavramlar

LINQ sorgu ifadelerini (C# Programlama Kılavuzu)

Birleşim işlemleri