C#在LINQ中使用GroupBy实现数据分组

2019-08-17 12:36

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 Students = new 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接口的对象 /// TKey代表分组标识的类型,TElement代表分组中单个数据对象的类型

var QueryStudentCity = from student in Students group student by student.City;

/// QueryStudentCity类型为:IGrouping /// 为了分组现时所有数据,需要嵌套两层循环(两个泛型接口) /// 外层循环遍历每个组,内层循环遍历每个组中的元素 foreach (var CityGroup in QueryStudentCity) {

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(); } } }


C#在LINQ中使用GroupBy实现数据分组.doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:创卫资料 街道病媒生物防制资料模板

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: