using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
List<Student> Students = GetStudents();
//group by 一个字段
var query1 = from a in Students
group a by a.SchoolID into b
select new
{
SchoolID = b.Key,
Count = b.Count()
};
//group by 多个字段
var query2 = from a in Students
group a by new { SchoolID = a.SchoolID, SchoolName = a.SchoolName } into b
select new
{
SchoolID = b.Key.SchoolID,
SchoolName = b.Key.SchoolName,
Count = b.Count()
};
//group by 能获取子集合
var query3 = Students.GroupBy(a => new { SchoolID = a.SchoolID, SchoolName = a.SchoolName });
if (query3.Count() > 0)
{
foreach (var item in query3)
{
int SchoolID = item.Key.SchoolID;
string SchoolName = item.Key.SchoolName;
List<Student> list = item.ToList();
}
}
}
private static List<Student> GetStudents()
{
List<Student> students = new List<Student>();
students.Add(new Student(1, "student1", 1, "学校1"));
students.Add(new Student(2, "student2", 1, "学校1"));
students.Add(new Student(3, "student3", 2, "学校2"));
students.Add(new Student(4, "student4", 2, "学校2"));
students.Add(new Student(5, "student5", 3, "学校3"));
return students;
}
}
public class Student
{
public Student() { }
public Student(int _studentID, string _studentName, int _schoolID, string _schoolName)
{
this.StudentID = _studentID;
this.StudentName = _studentName;
this.SchoolID = _schoolID;
this.SchoolName = _schoolName;
}
public int StudentID { get; set; }
public string StudentName { get; set; }
public int SchoolID { get; set; }
public string SchoolName { get; set; }
}
}
group by多个对象
var test = from l in list
join j in existsJobList on l.JobName equals j.Code
join d in existsDeptList on l.DeptCode equals d.Code
group new { l, j, d }
by new { PositionName = l.PositionName, JobTitleId = j.JobTitleId, DeptId = d.DeptId } into b
select new
{
PositionName = b.Key.PositionName,
JobTitleId = b.Key.JobTitleId,
DeptId = b.Key.DeptId,
};