热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

linq操作符:分组操作符

分组是根据一个特定的值将序列中的元素进行分组。LINQ只包含一个分组操作符:GroupBy。GroupBy操作符类似于T-SQL语言中的GroupBy语句。来看看GroupBy的方

分组是根据一个特定的值将序列中的元素进行分组。LINQ只包含一个分组操作符:GroupBy。GroupBy操作符类似于T-SQL语言中的Group By语句。来看看GroupBy的方法定义:



1 public static IEnumerable> GroupBy(this IEnumerable source, Func keySelector);
2 public static IEnumerable> GroupBy(this IEnumerable source, Func keySelector,
IEqualityComparer comparer);


 从方法定义中可以看出:GroupBy的返回值类型是:IEnumerable>。其元素类型是IGrouping。TKey属性代表了分组时使用的关键值,TSource属性代表了分组之后的元素集合。遍历IGrouping元素可以读取到每一个TSource类型。看下面的例子:


1、定义Product类,其定义如下:



 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace GroupOperation
8 {
9 public class Product
10 {
11 public int Id { get; set; }
12 public int CategoryId { get; set; }
13 public string Name { get; set; }
14 public double Price { get; set; }
15 public DateTime CreateTime { get; set; }
16 }
17 }


 2、在Main()方法中调用



 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace GroupOperation
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 List listProduct = new List()
14 {
15 new Product(){Id=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
16 new Product(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
17 new Product(){Id=3,CategoryId=2, Name="活着", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
18 new Product(){Id=4,CategoryId=3, Name="高等数学", Price=97,CreateTime=DateTime.Now.AddMonths(-1)},
19 new Product(){Id=5,CategoryId=6, Name="国家宝藏", Price=52.8,CreateTime=DateTime.Now.AddMonths(-1)}
20 };
21
22 // 查询表达式
23 var listExpress = from p in listProduct group p by p.CategoryId;
24 Console.WriteLine("输出查询表达式结果");
25 foreach (var item in listExpress)
26 {
27 Console.WriteLine($"CategoryId:{item.Key}");
28 foreach(var p in item)
29 {
30 Console.WriteLine($"ProduceName:{p.Name},ProductPrice:{p.Price},PublishTime:{p.CreateTime}");
31 }
32 }
33 Console.WriteLine("***************************************");
34 // 查询方法
35 var listFun = listProduct.GroupBy(p => p.CategoryId);
36 Console.WriteLine("输出方法语法结果");
37 foreach (var item in listFun)
38 {
39 Console.WriteLine($"CategoryId:{item.Key}");
40 foreach (var p in item)
41 {
42 Console.WriteLine($"ProduceName:{p.Name},ProductPrice:{p.Price},PublishTime:{p.CreateTime}");
43 }
44 }
45 Console.ReadKey();
46 }
47 }
48 }


 结果:


技术分享图片


 下面在来看看多个分组条件的例子。



 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace GroupOperation
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 List listProduct = new List()
14 {
15 new Product(){Id=1,CategoryId=1, Name="C#高级编程第10版", Price=100.67,CreateTime=DateTime.Now},
16 new Product(){Id=2,CategoryId=1, Name="Redis开发和运维", Price=69.9,CreateTime=DateTime.Now.AddDays(-19)},
17 new Product(){Id=3,CategoryId=2, Name="活着", Price=57,CreateTime=DateTime.Now.AddMonths(-3)},
18 new Product(){Id=4,CategoryId=3, Name="高等数学", Price=97,CreateTime=DateTime.Now.AddMonths(-1)},
19 new Product(){Id=5,CategoryId=6, Name="国家宝藏", Price=52.8,CreateTime=DateTime.Now.AddMonths(-1)}
20 };
21
22 // 查询表达式
23 var list = from p in listProduct group p by new { p.CategoryId, p.Price };
24 Console.WriteLine("查询表达式方式1输出:");
25 foreach (var item in list)
26 {
27 Console.WriteLine("key:" + item.Key);
28 foreach (var subItem in item)
29 {
30 Console.WriteLine($"ProduceName:{subItem.Name},ProductPrice:{subItem.Price},PublishTime:{subItem.CreateTime}");
31 }
32 }
33 var listExpress = from p in listProduct
34 group p by new { p.CategoryId, p.Price } into r // 使用into把数据填充到局部变量r中,然后select筛选数据
35 select new { key = r.Key, ListGroup = r.ToList() };
36 Console.WriteLine("查询表达式方式2输出:");
37 foreach(var item in listExpress)
38 {
39 Console.WriteLine("key:"+item.key);
40 foreach (var subItem in item.ListGroup)
41 {
42 Console.WriteLine($"ProduceName:{subItem.Name},ProductPrice:{subItem.Price},PublishTime:{subItem.CreateTime}");
43 }
44 }
45
46 // 方法语法
47 var listFun = listProduct.GroupBy(p => new { p.CategoryId, p.Price }).Select(g => new { key = g.Key, ListGroup = g.ToList() });
48 Console.WriteLine("方法语法输出:");
49 foreach (var item in listFun)
50 {
51 Console.WriteLine("key:" + item.key);
52 foreach (var subItem in item.ListGroup)
53 {
54 Console.WriteLine($"ProduceName:{subItem.Name},ProductPrice:{subItem.Price},PublishTime:{subItem.CreateTime}");
55 }
56 }
57
58 Console.ReadKey();
59 }
60 }
61 }


 结果:


技术分享图片


 

linq操作符:分组操作符



推荐阅读
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • PHP 编程疑难解析与知识点汇总
    本文详细解答了 PHP 编程中的常见问题,并提供了丰富的代码示例和解决方案,帮助开发者更好地理解和应用 PHP 知识。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • This guide provides a comprehensive step-by-step approach to successfully installing the MongoDB PHP driver on XAMPP for macOS, ensuring a smooth and efficient setup process. ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • PHP 5.2.5 安装与配置指南
    本文详细介绍了 PHP 5.2.5 的安装和配置步骤,帮助开发者解决常见的环境配置问题,特别是上传图片时遇到的错误。通过本教程,您可以顺利搭建并优化 PHP 运行环境。 ... [详细]
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 深入理解 SQL 视图、存储过程与事务
    本文详细介绍了SQL中的视图、存储过程和事务的概念及应用。视图为用户提供了一种灵活的数据查询方式,存储过程则封装了复杂的SQL逻辑,而事务确保了数据库操作的完整性和一致性。 ... [详细]
  • Python 异步编程:深入理解 asyncio 库(上)
    本文介绍了 Python 3.4 版本引入的标准库 asyncio,该库为异步 IO 提供了强大的支持。我们将探讨为什么需要 asyncio,以及它如何简化并发编程的复杂性,并详细介绍其核心概念和使用方法。 ... [详细]
  • 本文详细介绍了Java中org.neo4j.helpers.collection.Iterators.single()方法的功能、使用场景及代码示例,帮助开发者更好地理解和应用该方法。 ... [详细]
  • Windows服务与数据库交互问题解析
    本文探讨了在Windows 10(64位)环境下开发的Windows服务,旨在定期向本地MS SQL Server (v.11)插入记录。尽管服务已成功安装并运行,但记录并未正确插入。我们将详细分析可能的原因及解决方案。 ... [详细]
  • 本文详细介绍了 GWT 中 PopupPanel 类的 onKeyDownPreview 方法,提供了多个代码示例及应用场景,帮助开发者更好地理解和使用该方法。 ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • 本文详细介绍如何使用Python进行配置文件的读写操作,涵盖常见的配置文件格式(如INI、JSON、TOML和YAML),并提供具体的代码示例。 ... [详细]
author-avatar
i89379844
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有