博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Linq 中按照多个值进行分组(GroupBy)
阅读量:4677 次
发布时间:2019-06-09

本文共 1491 字,大约阅读时间需要 4 分钟。

/// 要查询的对象class Employee {   public int ID { get;set; }   public string FName { get; set; }   public int Age { get; set; }   public char Sex { get; set; }}

如果对这个类的Age和Sex的连个字段进行分组,方法如下:

// 先造一些数据List
empList = new List
();empList.Add(new Employee() { ID = 1, FName = "John", Age = 23, Sex = 'M'});empList.Add(new Employee() { ID = 2, FName = "Mary", Age = 25, Sex = 'F'});empList.Add(new Employee() { ID = 3, FName = "Amber", Age = 23, Sex = 'M'});empList.Add(new Employee() { ID = 4, FName = "Kathy", Age = 25, Sex = 'M'});empList.Add(new Employee() { ID = 5, FName = "Lena", Age = 27, Sex = 'F'});empList.Add(new Employee() { ID = 6, FName = "Bill", Age = 28, Sex = 'M'});empList.Add(new Employee() { ID = 7, FName = "Celina", Age = 27, Sex = 'F'});empList.Add(new Employee() { ID = 8, FName = "John", Age = 28, Sex = 'M'});

接下来的做法是:

// 实现多key分组的扩展函数版本var sums = empList         .GroupBy(x => new { x.Age, x.Sex })         .Select(group => new {            Peo = group.Key, Count = group.Count()         });foreach (var employee in sums) {   Console.WriteLine(employee.Count + ": " + employee.Peo);}// 实现多key分组的lambda版本var sums2 = from emp in empList            group emp by new { emp.Age, emp.Sex } into g            select new { Peo = g.Key, Count = g.Count() };foreach (var employee in sums) {   Console.WriteLine(employee.Count + ": " + employee.Peo);}

这个例子中就充分利用了匿名类型

转载于:https://www.cnblogs.com/aaa6818162/archive/2011/12/12/2284867.html

你可能感兴趣的文章
C#基础
查看>>
ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 15. 用户管理
查看>>
杭电3466————DP之01背包(对状态转移方程的更新理解)
查看>>
ASP.NET生命周期详解(转)
查看>>
EntityFramework 7 Left Join Where Select 奇怪问题
查看>>
关于static静态块的使用和static list的使用
查看>>
spring读取配置文件的几种方式
查看>>
从P1到P7——我在淘宝这7年(转)
查看>>
CRM 2011 Distribute Workflow Activity (MSCRM 2011 分派工作流活动)
查看>>
Qt for Android(转)
查看>>
C++大作业之链表实现的高精度加法,减法,和数组实现的高精度乘法。
查看>>
关于招聘的最新信息
查看>>
Python_列表,元组和字典的异同
查看>>
第十六讲:适配器模式
查看>>
java之网络爬虫介绍(非原创)
查看>>
hive-jdbc获取查询日志慢的问题发现与解决
查看>>
真正的语言能用一句代码输出三角形
查看>>
电子时钟,骷髅时钟
查看>>
优化页面加载速度
查看>>
【机器学习详解】SMO算法剖析(转载)
查看>>