c# linq goup by实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;


namespace WebApplication22
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindStudents();
            }
        }
        /// <summary>
        /// Binding the number of students in each school.
        /// </summary>
        private void BindStudents()
        {
            GridView1.DataSource = GetStudentCount();
            GridView1.DataBind();
        }
        /// <summary>
        /// Obtain the number of students in each school.
        /// </summary>
        /// <returns></returns>
        private IList GetStudentCount()
        {
            List<Student> Students = GetStudents();
            var query = from a in Students
                        group a by a.SchoolID into b
                        select new
                        {
                            SchoolID = b.Key,
                            TotalPenNumer=b.Sum(c=>c.PenNumber)
                        };
            return query.ToList();
        }
        /// <summary>
        /// Get the list of students.
        /// </summary>
        /// <returns></returns>
        private List<Student> GetStudents()
        {
            List<Student> students = new List<Student>();
            students.Add(new Student(1, "student1", 1, 1));
            students.Add(new Student(2, "student2", 2, 1));
            students.Add(new Student(3, "student3", 3, 2));
            students.Add(new Student(4, "student4", 4, 3));
            students.Add(new Student(5, "student5", 5, 3));
            students.Add(new Student(6, "student6", 6, 3));
            return students;
        }
    }
    /// <summary>
    /// Class of student.
    /// </summary>
    public class Student
    {
        public Student() { }
        public Student(int _studentID, string _studentName,int _penNumber, int _schoolID)
        {
            this.StudentID = _studentID;
            this.StudentName = _studentName;
            this.PenNumber = _penNumber;
            this.SchoolID = _schoolID;
        }
        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public int PenNumber { get; set; }
        public int SchoolID { get; set; }
    }
}

你可能感兴趣的:(c# linq goup by实例)