C# Linq源码分析之Take(五)
概要
本文在C# Linq源码分析之Take(四)的基础上继续从源码角度分析Take的优化方法,主要分析Where.Select.Take的使用案例。
Where.Select.Take的案例分析
该场景模拟我们显示中将EF中与数据库关联的对象进行过滤,然后转换成Web前端需要的对象,并分页的情况。
studentList.Where(x => x.MathResult >= 90).Select(x => new {x.Name,x.MathResult}).Take(3).ToList().ForEach(x=>Console.WriteLine(x.Name + x.MathResult));
找到数学90分以上的学生,获取学生的姓名和数学成绩,每次只取前三个学生。并将学生信息打印。Student类的代码请见附录。
源码流程分析
第一步进入Where方法,返回WhereListIterator对象;
第二步进入Select方法,将Where和Select两个操作合并,返回WhereSelectListIterator对象;
第三步进入Take方法,调用takeIterator方法;由于人WhereSelectListIterator并没有实现IPartition接口和IList接口,所以无法再进行操作合并,只能返回EnumerablePartition对象。
private static IEnumerable<TSource> takeIterator<TSource>(IEnumerable<TSource> source, int count){Debug.Assert(count > 0);returnsource is IPartition<TSource> partition ? partition.Take(count) :source is IList<TSource> sourceList ? new ListPartition<TSource>(sourceList, 0, count - 1) :new EnumerablePartition<TSource>(source, 0, count - 1);}
第四步进入ToList方法
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source){if (source == null){ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);}return source is IIListProvider<TSource> listProvider ? listProvider.ToList() : new List<TSource>(source);}
此时的source是EnumerablePartition对象,它实现了IPartition接口,而IPartition接口继承了IIListProvider接口,所以可以调用自己的ToList方法;
public List<TSource> ToList()
{var list = new List<TSource>();using (IEnumerator<TSource> en = _source.GetEnumerator()){if (SkipBeforeFirst(en) && en.MoveNext()){int remaining = Limit - 1; // Max number of items left, not counting the current element.int comparand = HasLimit ? 0 : int.MinValue; // If we don't have an upper bound, have the comparison always return true.do{remaining--;list.Add(en.Current);}while (remaining >= comparand && en.MoveNext());}}return list;
}
- 定义迭代器en,此时的_source是WhereSelectListIterator对象;
- 该ToList方法同样支持Skip,所以要判断迭代器的起始位置是不是从第一个开始;
- 每次迭代,首先从WhereSelectListIterator迭代器中返回一个符合过滤条件,并完成Selector操作的元素,存入list,直到list中包含三个元素,返回执行结果。
虽然WhereSelectListIterator没有实现IPartition接口,不能实现一次迭代,完成全部操作,但是现有的流程性能并不差,因为WhereSelectListIterator迭代器本身已经合并了过滤和投影操作,而且并不需要遍历所有元素,只要找到3个符合条件的元素即可。
我认为如果代码需要用到Take方法,尽量把它放到Linq的最后。这样做的好处是前面的Linq操作并不需要遍历全部的序列元素,只要得到Take方法中需要的元素个数即可。
本文中涉及的源码请见附录,关于WhereSelectListIterator的合并优化操作,更多详细内容,请参考C# LINQ源码分析之Select
附录
Student类
public class Student {public string Id { get; set; }public string Name { get; set; }public string Classroom { get; set; }public int MathResult { get; set; }
}
IIListProvider接口
internal interface IIListProvider<TElement> : IEnumerable<TElement>
{TElement[] ToArray();List<TElement> ToList();int GetCount(bool onlyIfCheap);
}
IPartition接口
internal interface IPartition<TElement> : IIListProvider<TElement>
{IPartition<TElement> Skip(int count);IPartition<TElement> Take(int count);TElement? TryGetElementAt(int index, out bool found);TElement? TryGetFirst(out bool found);TElement? TryGetLast(out bool found);
}
EnumerablePartition类
private sealed class EnumerablePartition<TSource> : Iterator<TSource>, IPartition<TSource>{private readonly IEnumerable<TSource> _source;private readonly int _minIndexInclusive;private readonly int _maxIndexInclusive; // -1 if we want everything past _minIndexInclusive.// If this is -1, it's impossible to set a limit on the count.private IEnumerator<TSource>? _enumerator;internal EnumerablePartition(IEnumerable<TSource> source, int minIndexInclusive, int maxIndexInclusive){Debug.Assert(source != null);Debug.Assert(!(source is IList<TSource>), $"The caller needs to check for {nameof(IList<TSource>)}.");Debug.Assert(minIndexInclusive >= 0);Debug.Assert(maxIndexInclusive >= -1);// Note that although maxIndexInclusive can't grow, it can still be int.MaxValue.// We support partitioning enumerables with > 2B elements. For example, e.Skip(1).Take(int.MaxValue) should work.// But if it is int.MaxValue, then minIndexInclusive must != 0. Otherwise, our count may overflow.Debug.Assert(maxIndexInclusive == -1 || (maxIndexInclusive - minIndexInclusive < int.MaxValue), $"{nameof(Limit)} will overflow!");Debug.Assert(maxIndexInclusive == -1 || minIndexInclusive <= maxIndexInclusive);_source = source;_minIndexInclusive = minIndexInclusive;_maxIndexInclusive = maxIndexInclusive;}// If this is true (e.g. at least one Take call was made), then we have an upper bound// on how many elements we can have.private bool HasLimit => _maxIndexInclusive != -1;private int Limit => unchecked((_maxIndexInclusive + 1) - _minIndexInclusive); // This is that upper bound.public override Iterator<TSource> Clone() =>new EnumerablePartition<TSource>(_source, _minIndexInclusive, _maxIndexInclusive);public override void Dispose(){if (_enumerator != null){_enumerator.Dispose();_enumerator = null;}base.Dispose();}public int GetCount(bool onlyIfCheap){if (onlyIfCheap){return -1;}if (!HasLimit){// If HasLimit is false, we contain everything past _minIndexInclusive.// Therefore, we have to iterate the whole enumerable.//return Math.Max(_source.Count()- _minIndexInclusive, 0);return 0;}using (IEnumerator<TSource> en = _source.GetEnumerator()){// We only want to iterate up to _maxIndexInclusive + 1.// Past that, we know the enumerable will be able to fit this partition,// so the count will just be _maxIndexInclusive + 1 - _minIndexInclusive.// Note that it is possible for _maxIndexInclusive to be int.MaxValue here,// so + 1 may result in signed integer overflow. We need to handle this.// At the same time, however, we are guaranteed that our max count can fit// in an int because if that is true, then _minIndexInclusive must > 0.uint count = SkipAndCount((uint)_maxIndexInclusive + 1, en);Debug.Assert(count != (uint)int.MaxValue + 1 || _minIndexInclusive > 0, "Our return value will be incorrect.");return Math.Max((int)count - _minIndexInclusive, 0);}}public override bool MoveNext(){// Cases where GetEnumerator has not been called or Dispose has already// been called need to be handled explicitly, due to the default: clause.int taken = _state - 3;if (taken < -2){Dispose();return false;}switch (_state){case 1:_enumerator = _source.GetEnumerator();_state = 2;goto case 2;case 2:Debug.Assert(_enumerator != null);if (!SkipBeforeFirst(_enumerator)){// Reached the end before we finished skipping.break;}_state = 3;goto default;default:Debug.Assert(_enumerator != null);if ((!HasLimit || taken < Limit) && _enumerator.MoveNext()){if (HasLimit){// If we are taking an unknown number of elements, it's important not to increment _state.// _state - 3 may eventually end up overflowing & we'll hit the Dispose branch even though// we haven't finished enumerating._state++;}_current = _enumerator.Current;return true;}break;}Dispose();return false;}public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) =>new SelectIPartitionIterator<TSource, TResult>(this, selector);public IPartition<TSource> Skip(int count){int minIndex = unchecked(_minIndexInclusive + count);if (!HasLimit){if (minIndex < 0){// If we don't know our max count and minIndex can no longer fit in a positive int,// then we will need to wrap ourselves in another iterator.// This can happen, for example, during e.Skip(int.MaxValue).Skip(int.MaxValue).return new EnumerablePartition<TSource>(this, count, -1);}}else if ((uint)minIndex > (uint)_maxIndexInclusive){// If minIndex overflows and we have an upper bound, we will go down this branch.// We know our upper bound must be smaller than minIndex, since our upper bound fits in an int.// This branch should not be taken if we don't have a bound.return EmptyPartition<TSource>.Instance;}Debug.Assert(minIndex >= 0, $"We should have taken care of all cases when {nameof(minIndex)} overflows.");return new EnumerablePartition<TSource>(_source, minIndex, _maxIndexInclusive);}public IPartition<TSource> Take(int count){int maxIndex = unchecked(_minIndexInclusive + count - 1);if (!HasLimit){if (maxIndex < 0){// If we don't know our max count and maxIndex can no longer fit in a positive int,// then we will need to wrap ourselves in another iterator.// Note that although maxIndex may be too large, the difference between it and// _minIndexInclusive (which is count - 1) must fit in an int.// Example: e.Skip(50).Take(int.MaxValue).return new EnumerablePartition<TSource>(this, 0, count - 1);}}else if (unchecked((uint)maxIndex >= (uint)_maxIndexInclusive)){// If we don't know our max count, we can't go down this branch.// It's always possible for us to contain more than count items, as the rest// of the enumerable past _minIndexInclusive can be arbitrarily long.return this;}Debug.Assert(maxIndex >= 0, $"We should have taken care of all cases when {nameof(maxIndex)} overflows.");return new EnumerablePartition<TSource>(_source, _minIndexInclusive, maxIndex);}public TSource? TryGetElementAt(int index, out bool found){// If the index is negative or >= our max count, return early.if (index >= 0 && (!HasLimit || index < Limit)){using (IEnumerator<TSource> en = _source.GetEnumerator()){Debug.Assert(_minIndexInclusive + index >= 0, $"Adding {nameof(index)} caused {nameof(_minIndexInclusive)} to overflow.");if (SkipBefore(_minIndexInclusive + index, en) && en.MoveNext()){found = true;return en.Current;}}}found = false;return default;}public TSource? TryGetFirst(out bool found){using (IEnumerator<TSource> en = _source.GetEnumerator()){if (SkipBeforeFirst(en) && en.MoveNext()){found = true;return en.Current;}}found = false;return default;}public TSource? TryGetLast(out bool found){using (IEnumerator<TSource> en = _source.GetEnumerator()){if (SkipBeforeFirst(en) && en.MoveNext()){int remaining = Limit - 1; // Max number of items left, not counting the current element.int comparand = HasLimit ? 0 : int.MinValue; // If we don't have an upper bound, have the comparison always return true.TSource result;do{remaining--;result = en.Current;}while (remaining >= comparand && en.MoveNext());found = true;return result;}}found = false;return default;}public List<TSource> ToList(){var list = new List<TSource>();using (IEnumerator<TSource> en = _source.GetEnumerator()){if (SkipBeforeFirst(en) && en.MoveNext()){int remaining = Limit - 1; // Max number of items left, not counting the current element.int comparand = HasLimit ? 0 : int.MinValue; // If we don't have an upper bound, have the comparison always return true.do{remaining--;list.Add(en.Current);}while (remaining >= comparand && en.MoveNext());}}return list;}private bool SkipBeforeFirst(IEnumerator<TSource> en) => SkipBefore(_minIndexInclusive, en);private static bool SkipBefore(int index, IEnumerator<TSource> en) => SkipAndCount(index, en) == index;private static int SkipAndCount(int index, IEnumerator<TSource> en){Debug.Assert(index >= 0);return (int)SkipAndCount((uint)index, en);}private static uint SkipAndCount(uint index, IEnumerator<TSource> en){Debug.Assert(en != null);for (uint i = 0; i < index; i++){if (!en.MoveNext()){return i;}}return index;}public TSource[] ToArray(){throw new NotImplementedException();}}
相关文章:

C# Linq源码分析之Take(五)
概要 本文在C# Linq源码分析之Take(四)的基础上继续从源码角度分析Take的优化方法,主要分析Where.Select.Take的使用案例。 Where.Select.Take的案例分析 该场景模拟我们显示中将EF中与数据库关联的对象进行过滤,然后转换成Web…...

性能监控-grafana+prometheus+node_exporter
Prometheus是一个开源的系统监控和报警工具。它由SoundCloud开发并于2012年发布,后来成为了一个独立的开源项目,并得到了广泛的应用和支持。 Prometheus的主要功能包括采集和存储各种系统和应用程序的监控数据,并提供强大的查询语言PromQL来…...

(STM32H5系列)STM32H573RIT6、STM32H573RIV6、STM32H573ZIT6嵌入式微控制器基于Cortex®-M33内核
一、应用 工业(PLC、工业电机控制、泵和压缩机) 智能家居(空调、冰箱、冰柜、中央警报系统、洗衣机) 个人电子产品(键盘、智能手机、物联网标签、跟踪设备) 智能城市(工业通信、照明控制、数字…...
mysql配置bind-address不生效
1、前言 因为要ip直接访问mysql,故去修改bind-address参数,按照mysql配置文件查找顺序是:/etc/my.cnf、/etc/mysql/my.cnf、~/.my.cnf,服务器上没有 /etc/my.cnf文件,故去修改 /etc/mysql/my.cnf文件,但是一…...

Linux相关指令(下)
cat指令 查看目标文件的内容 常用选项: -b 对非空输出行编号 -n 对输出的所有行编号 -s 不输出多行空行 一个重要思想:linux下一切皆文件,如显示器文件,键盘文件 cat默认从键盘中读取数据再打印 退出可以ctrlc 输入重定向<…...
Codeforces Round 855 (Div 3)(A - F)
Codeforces Round 855 (Div. 3)(A - F) Codeforces Round 855 (Div. 3) A. Is It a Cat?(思维) 思路:先把所有字母变成小写方便判断 , 然后把每一部分取一个字母出来 , 判断和‘meow’是否相同即可。 复杂度 O ( n…...
Friend.tech(FT):社交媒体金融的未来,真的如此美好吗?
Friend.tech(FT)是一个在2023年8月10日正式推出的社交金融平台,它的特点在于允许用户购买和出售创作者的股票(shares),这些股票赋予用户访问创作者内容的权利。FT的推出引发了广泛的关注,吸引了…...

yolov7中Concat之后加注意力模块(最复杂的情况)
1、common.py中找到Concat模块,复制一份 2、要传参进来,dim通道数 3、然后找yolo.py模块,添加 4、yaml里替换 5、和加的位置也有关系...

解除百度安全验证
使用chrome浏览器用百度浏览时,一直弹百度安全验证: 在设置里进行重置: 然后重启浏览器就可以了。...
Codeforces Round 731 (Div 3)(A - F)
Codeforces Round 731 (Div. 3)(A - F) Dashboard - Codeforces Round 731 (Div. 3) - Codeforces A. Shortest Path with Obstacle(思维) 思路:显然要计算 A → B 之间的曼哈顿距离 , 要绕开 F 当且仅当 AB形成的直线平行于坐…...
Python的sort()与sorted()函数详解
目录 sort()函数 sorted()函数 key参数 区别 sort()函数 sort()方法:该方法用于原地对列表进行排序,即直接在原始列表上进行排序操作,并不返回一个新的列表。 my_l…...

用python实现基本数据结构【04/4】
说明 如果需要用到这些知识却没有掌握,则会让人感到沮丧,也可能导致面试被拒。无论是花几天时间“突击”,还是利用零碎的时间持续学习,在数据结构上下点功夫都是值得的。那么Python 中有哪些数据结构呢?列表、字典、集…...
“必抓!”算法
一个程序员一生中可能会邂逅各种各样的算法,但总有那么几种,是作为一个程序员一定会遇见且大概率需要掌握的算法。今天就来聊聊这些十分重要的“必抓!”算法吧~ 你可以从以下几个方面进行创作(仅供参考) 一ÿ…...

【监控系统】Promethus整合Alertmanager监控告警邮件通知
【监控系统】Promethus整合Alertmanager监控告警邮件通知 Alertmanager是一种开源软件,用于管理和报警监视警报。它与Prometheus紧密集成,后者是一种流行的开源监视和警报系统。Alertmanager从多个源接收警报和通知,并根据一组配置规则来决定…...

【韩顺平】Linux基础
目录 1.网络连接三种方式 1.1 桥接模式:虚拟系统可以和外部系统通讯,但是容易造成IP冲突【1-225】 1.2 NAT模式:网络地址转换模式。虚拟系统可以和外部系统通讯,不造成IP冲突。 1.3 主机模式:独立的系统。 2.虚拟机…...

好奇一下各个大模型对华为mate60系列的看法
目前华为Mate60系列手机已上市并获抢购,个人觉得很不错,很好奇各个AI大模型对此事的看法,于是对chatGPT、文心一言、讯飞星火进行了一下粗浅的测试。 题目一(看看三个模型的综合分析能力) “目前华为Mate60系列手机已…...

UMA 2 - Unity Multipurpose Avatar☀️五.如何使用别人的Recipe和创建自己的服饰Recipe
文章目录 🟥 使用别人的Recipe1️⃣ 导入UMA资源效果展示2️⃣ 更新Library3️⃣ 试一下吧🟧 创建自己的服饰Recipe1️⃣ 创建自己的服饰Recipe2️⃣ 选择应用到的Base Recipe3️⃣ 指定显示名 / 佩戴位置 / 隐藏部位4️⃣ 给该服饰Recipe指定Slot / Overlay🚩 赋予Slot�…...
代码随想录训练营第五十六天| 583. 两个字符串的删除操作 、72. 编辑距离
583. 两个字符串的删除操作 题目链接/文章讲解/视频讲解:代码随想录 1.代码展示 //583.两个字符串的删除操作 int minDistance(string word1, string word2) {//step1 构建dp数组,dp[i][j]的含义是要使以i-1为结尾的word1和以j-1为结尾的word2//删除其元…...
hive解决了什么问题
hive出现的原因 Hive 出现的原因主要有以下几个: 传统数据仓库无法处理大规模数据:传统的数据仓库通常采用关系型数据库作为底层存储,这种数据库在处理大规模数据时效率较低。MapReduce 难以使用:MapReduce 是一种分布式计算框架…...

Lumion 和 Enscape 应该选择怎样的笔记本电脑?
Lumion 和 Enscape实时渲染对配置要求高,本地配置不够,如何快速解决: 本地普通电脑可一键申请高性能工作站,资产安全保障,供软件中心,各种软件插件一键获取,且即开即用,使用灵活&am…...

华为云AI开发平台ModelArts
华为云ModelArts:重塑AI开发流程的“智能引擎”与“创新加速器”! 在人工智能浪潮席卷全球的2025年,企业拥抱AI的意愿空前高涨,但技术门槛高、流程复杂、资源投入巨大的现实,却让许多创新构想止步于实验室。数据科学家…...
【网络】每天掌握一个Linux命令 - iftop
在Linux系统中,iftop是网络管理的得力助手,能实时监控网络流量、连接情况等,帮助排查网络异常。接下来从多方面详细介绍它。 目录 【网络】每天掌握一个Linux命令 - iftop工具概述安装方式核心功能基础用法进阶操作实战案例面试题场景生产场景…...
Python爬虫实战:研究feedparser库相关技术
1. 引言 1.1 研究背景与意义 在当今信息爆炸的时代,互联网上存在着海量的信息资源。RSS(Really Simple Syndication)作为一种标准化的信息聚合技术,被广泛用于网站内容的发布和订阅。通过 RSS,用户可以方便地获取网站更新的内容,而无需频繁访问各个网站。 然而,互联网…...
基于Uniapp开发HarmonyOS 5.0旅游应用技术实践
一、技术选型背景 1.跨平台优势 Uniapp采用Vue.js框架,支持"一次开发,多端部署",可同步生成HarmonyOS、iOS、Android等多平台应用。 2.鸿蒙特性融合 HarmonyOS 5.0的分布式能力与原子化服务,为旅游应用带来…...

2.Vue编写一个app
1.src中重要的组成 1.1main.ts // 引入createApp用于创建应用 import { createApp } from "vue"; // 引用App根组件 import App from ./App.vue;createApp(App).mount(#app)1.2 App.vue 其中要写三种标签 <template> <!--html--> </template>…...

【单片机期末】单片机系统设计
主要内容:系统状态机,系统时基,系统需求分析,系统构建,系统状态流图 一、题目要求 二、绘制系统状态流图 题目:根据上述描述绘制系统状态流图,注明状态转移条件及方向。 三、利用定时器产生时…...

NFT模式:数字资产确权与链游经济系统构建
NFT模式:数字资产确权与链游经济系统构建 ——从技术架构到可持续生态的范式革命 一、确权技术革新:构建可信数字资产基石 1. 区块链底层架构的进化 跨链互操作协议:基于LayerZero协议实现以太坊、Solana等公链资产互通,通过零知…...
【学习笔记】深入理解Java虚拟机学习笔记——第4章 虚拟机性能监控,故障处理工具
第2章 虚拟机性能监控,故障处理工具 4.1 概述 略 4.2 基础故障处理工具 4.2.1 jps:虚拟机进程状况工具 命令:jps [options] [hostid] 功能:本地虚拟机进程显示进程ID(与ps相同),可同时显示主类&#x…...

mysql已经安装,但是通过rpm -q 没有找mysql相关的已安装包
文章目录 现象:mysql已经安装,但是通过rpm -q 没有找mysql相关的已安装包遇到 rpm 命令找不到已经安装的 MySQL 包时,可能是因为以下几个原因:1.MySQL 不是通过 RPM 包安装的2.RPM 数据库损坏3.使用了不同的包名或路径4.使用其他包…...
大语言模型(LLM)中的KV缓存压缩与动态稀疏注意力机制设计
随着大语言模型(LLM)参数规模的增长,推理阶段的内存占用和计算复杂度成为核心挑战。传统注意力机制的计算复杂度随序列长度呈二次方增长,而KV缓存的内存消耗可能高达数十GB(例如Llama2-7B处理100K token时需50GB内存&a…...