C#在LINQ中使用GroupBy实现数据分组
using System;
using System.Collections.Generic; using System.Linq; using System.Text;
namespace UseGroup {
//-----------------------------------------------------------------------------------------------------
public class Student {
public string Name { get; set; } public string City { get; set; } }
class Program {
static void Main(string[] args) {
/// 数据源
List
new Student { Name=\张三\, City=\北京\ }, new Student { Name=\李四\, City=\上海\ }, new Student { Name=\王五\, City=\北京\ }, new Student { Name=\赵六\, City=\重庆\ }, new Student { Name=\马七\, City=\北京\ }, new Student { Name=\牛八\, City=\上海\ }, new Student { Name=\杨九\, City=\北京\ }, new Student { Name=\阮十\, City=\广州\ }, new Student { Name=\萧十一\, City=\重庆\ }, new Student { Name=\伍十二\, City=\上海\ }, new Student { Name=\梁十三\, City=\广州\ }, new Student { Name=\黄十四\, City=\北京\ }, new Student { Name=\刘十五\, City=\重庆\ }, new Student { Name=\刀十六\, City=\上海\ }, new Student { Name=\元十七\, City=\重庆\ }, new Student { Name=\柳十八\, City=\北京\ }, new Student { Name=\吴十九\, City=\广州\ }, new Student { Name=\魏二十\, City=\上海\ } };
/// QueryStudentCity类型为:IEnumerable
/// group by本质上是实现IGrouping
var QueryStudentCity = from student in Students group student by student.City;
/// QueryStudentCity类型为:IGrouping
Console.WriteLine(\); Console.WriteLine(\在{0}的学生清单:\, CityGroup.Key);
int count = 0;
foreach (Student student in CityGroup) {
count++;
Console.WriteLine(\, count, student.Name, student.City); }
Console.WriteLine(\); }
Console.ReadKey(); } } }