Aracılığıyla paylaş


group tümcesi (C# Başvurusu)

group Yan tümcesi, bir dizi verir IGrouping eşleşen grubu için anahtar değeri sıfır veya daha fazla öğe içeren nesne.Örneğin, bir dizi her dizenin ilk harfini dizelerine göre gruplandırabilirsiniz.Bu durumda, ilk harfini anahtar ve bir türü olan char, depolanır ve Key özelliği her IGrouping nesne.Derleyici anahtar türü yorumlar.

Sorgu ifadesi ile sona erdirebilecek bir group yan tümcesi aşağıdaki örnekte gösterildiği gibi:

// Query variable is an IEnumerable<IGrouping<char, Student>> 
var studentQuery1 =
    from student in students
    group student by student.Last[0];

Her grup ek sorgu işlemleri gerçekleştirmek istiyorsanız, geçici bir tanımlayıcı kullanarak belirtebileceğiniz içine bağlamsal anahtar sözcüğü.Kullandığınızda into, sorgu ile devam etmek ve sonuçta ile ya da bitiş gerekir bir select deyimi ya da başka bir group yan tümcesi aşağıdaki alıntıda gösterildiği gibi:

// Group students by the first letter of their last name 
// Query variable is an IEnumerable<IGrouping<char, Student>> 
var studentQuery2 =
    from student in students
    group student by student.Last[0] into g
    orderby g.Key
    select g;

Daha da kullanımı örnekleri'ni tamamlamak group olan ve olmayan into bu konuda örnek bölümünde sağlanmıştır.

Bir grup sorgu sonuçlarını numaralandırma

Çünkü IGrouping tarafından üretilen nesnelerin bir group sorgu aslında listelerinin listesini, bir iç içe kullanmanız gerekir foreach her grup içindeki öğelere erişmek için döngü.Dış döngü Grup anahtarlarını ilerler ve iç döngü grubundaki her bir öğenin üzerinde sırayla dolaşır.Bir grup, bir anahtar ancak herhangi bir öğe olabilir.Aşağıdaki foreach önceki kod örnekleri sorguyu yürütür döngü:

// Iterate group items with a nested foreach. This IGrouping encapsulates 
// a sequence of Student objects, and a Key of type char. 
// For convenience, var can also be used in the foreach statement. 
foreach (IGrouping<char, Student> studentGroup in studentQuery2)
{
     Console.WriteLine(studentGroup.Key);
     // Explicit type for student could also be used here. 
     foreach (var student in studentGroup)
     {
         Console.WriteLine("   {0}, {1}", student.Last, student.First);
     }
 }

Anahtar türleri

Gibi bir dize, yerleşik bir sayısal tür veya kullanıcı tanımlı türü veya anonim tür adlı Grup anahtarlarını herhangi bir türü olabilir.

Dize göre gruplandırma

Önceki kod örnekleri kullanılan bir char.Dizgi anahtarını kolayca yerine, örneğin tam Soyadı belirtilmiş:

// Same as previous example except we use the entire last name as a key. 
// Query variable is an IEnumerable<IGrouping<string, Student>> 
 var studentQuery3 =
     from student in students
     group student by student.Last;

Bool göre gruplandırma

Aşağıdaki örnek, bir bool değeri iki gruba sonuçları bölmek bir anahtar kullanımını göstermektedir.Değer'de bir sub-expression tarafından üretilir Not group yan tümcesi.

class GroupSample1
{
    // The element type of the data source. 
    public class Student
    {
        public string First { get; set; }
        public string Last { get; set; }
        public int ID { get; set; }
        public List<int> Scores;
    }

    public static List<Student> GetStudents()
    {
        // Use a collection initializer to create the data source. Note that each element 
        //  in the list contains an inner sequence of scores.
        List<Student> students = new List<Student>
        {
           new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 72, 81, 60}},
           new Student {First="Claire", Last="O'Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
           new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {99, 89, 91, 95}},
           new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {72, 81, 65, 84}},
           new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {97, 89, 85, 82}} 
        };

        return students;

    }

    static void Main()
    {
        // Obtain the data source.
        List<Student> students = GetStudents();

        // Group by true or false. 
        // Query variable is an IEnumerable<IGrouping<bool, Student>> 
        var booleanGroupQuery =
            from student in students
            group student by student.Scores.Average() >= 80; //pass or fail! 

        // Execute the query and access items in each group 
        foreach (var studentGroup in booleanGroupQuery)
        {
            Console.WriteLine(studentGroup.Key == true ? "High averages" : "Low averages");
            foreach (var student in studentGroup)
            {
                Console.WriteLine("   {0}, {1}:{2}", student.Last, student.First, student.Scores.Average());
            }
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
  Low averages
   Omelchenko, Svetlana:77.5
   O'Donnell, Claire:72.25
   Garcia, Cesar:75.5
  High averages
   Mortensen, Sven:93.5
   Garcia, Debra:88.25
*/

Sayısal aralığına göre gruplandırma

Sonraki örnek, frekans aralığı temsil eden sayısal Grup anahtarlarını oluşturmak için bir ifade kullanır.Kullanımına dikkat edin izin içinde iki kez yöntemini çağırın gerekmez, bir yöntem depolamak için uygun bir konum sonuç, çağrı group yan tümcesi.Ayrıca, Not group "sıfıra" özel durumu önlemek için kodu Öğrenci sıfır ortalama yok emin olmak için denetler, yan tümcesi.Güvenle sorgu ifadelerde yöntemlerini kullanma hakkında daha fazla bilgi için bkz: Nasıl yapılır: Sorgu İfadelerinde Özel Durumları İşleme (C# Programlama Kılavuzu).

class GroupSample2
{
    // The element type of the data source. 
    public class Student
    {
        public string First { get; set; }
        public string Last { get; set; }
        public int ID { get; set; }
        public List<int> Scores;
    }

    public static List<Student> GetStudents()
    {
        // Use a collection initializer to create the data source. Note that each element 
        //  in the list contains an inner sequence of scores.
        List<Student> students = new List<Student>
        {
           new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 72, 81, 60}},
           new Student {First="Claire", Last="O'Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
           new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {99, 89, 91, 95}},
           new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {72, 81, 65, 84}},
           new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {97, 89, 85, 82}} 
        };

        return students;

    }

    // This method groups students into percentile ranges based on their 
    // grade average. The Average method returns a double, so to produce a whole 
    // number it is necessary to cast to int before dividing by 10.  
    static void Main()
    {
        // Obtain the data source.
        List<Student> students = GetStudents();

        // Write the query. 
        var studentQuery =
            from student in students
            let avg = (int)student.Scores.Average()
            group student by (avg == 0 ? 0 : avg / 10) into g
            orderby g.Key
            select g;            

        // Execute the query. 
        foreach (var studentGroup in studentQuery)
        {
            int temp = studentGroup.Key * 10;
            Console.WriteLine("Students with an average between {0} and {1}", temp, temp + 10);
            foreach (var student in studentGroup)
            {
                Console.WriteLine("   {0}, {1}:{2}", student.Last, student.First, student.Scores.Average());
            }
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
     Students with an average between 70 and 80
       Omelchenko, Svetlana:77.5
       O'Donnell, Claire:72.25
       Garcia, Cesar:75.5
     Students with an average between 80 and 90
       Garcia, Debra:88.25
     Students with an average between 90 and 100
       Mortensen, Sven:93.5
 */

Bileşik anahtarları göre gruplandırma

Anahtarına göre birden fazla Grup öğelerini istiyorsanız, bir bileşik anahtar kullanın.Bileşik anahtar anahtar öğe tutacak bir anonim tür veya adlandırılmış bir tür kullanarak oluşturun.Aşağıdaki örnekte, varsayalım bir sınıf Person adlı üyeleriyle bildirilen surname ve city.group Yan tümcesi kişiler ile aynı soyadını ve aynı şehirde her kümesinin oluşturulması ayrı bir grup neden olur.

group person by new {name = person.surname, city = person.city};

Sorgu değişkeni için başka bir yöntem başarılı olursa, adlandýrýlmýþ bir tür kullanın.Otomatik uygulanan özellikler tuşları kullanarak özel bir sınıf oluşturun ve sonra geçersiz kılma Equals ve GetHashCode yöntemleri.Bir yapı, bu durumda kesinlikle bu yöntemleri geçersiz kılmak sizde değil de kullanabilirsiniz.Daha fazla bilgi için bkz. Nasıl yapılır: Otomatik Uygulanan Özelliklerle Hafif bir Sınıf Uygulama (C# Programlama Kılavuzu) ve Nasıl yapılır: Bir Dizin Ağacında Yineleyen Dosyalar için Sorgu (LINQ).İkinci konu, adlandýrýlmýþ bir türde bir bileşik anahtar kullanımı gösterilmiştir bir kod örneği vardır.

Örnek

Aşağıdaki örnek, hiçbir ek sorgu mantığı gruplarına uygulandığında kaynak verileri gruplar halinde sipariş için standart desen gösterir.Bu bir gruplama olmadan bir devamı olarak adlandırılır.Dize dizisi öğeleri kendi ilk harfine göre gruplandırılır.Sorgu sonucu bir IGrouping içeren bir ortak türü Key türünde özellik char ve bir IEnumerable gruplama içindeki her öğeyi içeren koleksiyonu.

Sonucu, bir group yan tümcesinin sıraları dizisi.Bu nedenle, döndürülen her grup içindeki tek tek öğeleri erişmek için bir iç içe kullanmak foreach aşağıdaki örnekte gösterildiği gibi Grup anahtarlarını döngü içinde döngü.

class GroupExample1
{
    static void Main()
    {
        // Create a data source. 
        string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" };

        // Create the query. 
        var wordGroups =
            from w in words
            group w by w[0];

        // Execute the query. 
        foreach (var wordGroup in wordGroups)
        {
            Console.WriteLine("Words that start with the letter '{0}':", wordGroup.Key);
            foreach (var word in wordGroup)
            {
                Console.WriteLine(word);
            }
        }

        // Keep the console window open in debug mode
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }        
}
/* Output:
      Words that start with the letter 'b':
        blueberry
        banana
      Words that start with the letter 'c':
        chimpanzee
        cheese
      Words that start with the letter 'a':
        abacus
        apple
     */

Bu örneği kullanarak bunları oluşturduktan sonra ek mantık gruplarında gerçekleştirme gösterir bir devam ile into.Daha fazla bilgi için bkz. into (C# Başvurusu).Aşağıdaki örnek, her grup, yalnızca anahtar değeri olan bir ünlü seçmek için sorgular.

class GroupClauseExample2
{
    static void Main()
    {
        // Create the data source. 
        string[] words2 = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese", "elephant", "umbrella", "anteater" };

        // Create the query. 
        var wordGroups2 =
            from w in words2
            group w by w[0] into grps
            where (grps.Key == 'a' || grps.Key == 'e' || grps.Key == 'i'
                   || grps.Key == 'o' || grps.Key == 'u')
            select grps;

        // Execute the query. 
        foreach (var wordGroup in wordGroups2)
        {
            Console.WriteLine("Groups that start with a vowel: {0}", wordGroup.Key);
            foreach (var word in wordGroup)
            {
                Console.WriteLine("   {0}", word);
            }
        }

        // Keep the console window open in debug mode
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    Groups that start with a vowel: a
        abacus
        apple
        anteater
    Groups that start with a vowel: e
        elephant
    Groups that start with a vowel: u
        umbrella
*/

Notlar

Derleme zamanında group yan tümceleri dönüştürür çevrilmiş GroupBy``2 yöntemi.

Ayrıca bkz.

Görevler

Nasıl yapılır: İç İçe Geçmiş Grup Oluşturma (C# Programlama Kılavuzu)

Nasıl yapılır: Sorgu Sonuçlarını Gruplandırma (C# Programlama Kılavuzu)

Nasıl yapılır: Gruplandırma İşleminde Alt Sorgu Gerçekleştirme (C# Programlama Kılavuzu)

Başvuru

IGrouping

GroupBy``2

ThenBy``2

ThenByDescending``2

Kavramlar

LINQ Sorgu İfadeleri (C# Programlama Kılavuzu)

Diğer Kaynaklar

Sorgu Anahtar Sözcükleri (C# Başvurusu)