Home   Cover Cover Cover Cover
 

Query-Ausdruck mit Gruppierung

A06.cs
/* Query expression with grouping
   This example processes a list of students and collects all students that
   have the same year in their student ID into a group (the year in a
   student ID is made up by the first 4 digits of the 7 digit ID).
------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;

class Student {
  public string Name;
  public int Id;
  public string Field { get; set; }
  public Student() {}
  public Student(string name) { Name = name; }
}

public class A6 {
  
  public static void Main() {
    var students = new List< Student > {
      new Student { Name = "Bob Foster",   Id = 2008114, Field = "Computing" },
      new Student { Name = "Alice Miller", Id = 2008231, Field = "Mathematics" },
      new Student { Name = "Ann Malinsky", Id = 2008376, Field = "Computing" },
      new Student { Name = "John Dilbert", Id = 2008455, Field = "Chemistry" },
      new Student { Name = "Hugh Meyer",   Id = 2009004, Field = "Computing" },
      new Student { Name = "Robert Brown", Id = 2009057, Field = "Chemistry" },
      new Student { Name = "Jill Dawkins", Id = 2009196, Field = "Computing" },
      new Student { Name = "Susan Smith",  Id = 2009275, Field = "Mathematics" },
    };
    
    var result =
      from s in students
      let year = s.Id / 1000
      group s by year;
      
    foreach (var group in result) {
      Console.WriteLine(group.Key);
      foreach (Student s in group) {
        Console.WriteLine("  " + s.Name + " (" + s.Id + "), " + s.Field);
      }
    }
  }
}