说明:
针对长度较大的List对象,可以分组批量进行处理, 如:长度为1000的List
Source
/****************************************************************************** * 名称:List分组迭代器 * 说明:针对长度较大的List对象,可以分组批量进行处理 * 如:长度为1000的List<int>对象,可分为10组,每组100条,对数据进行业务逻辑处理 * 作者:Sybs * 时间:2018-10-15 * **************************************************************************/ namespace System.Collections.Generic { /// <summary> /// List分组迭代器 /// </summary> public class ListGroupIterator<T> { private int _groupsize = 1; /// <summary> /// 分组大小(缺省值为1) /// </summary> public int GroupSize { get => _groupsize; set => _groupsize = value < 1 ? 1 : value; } /// <summary> /// 分组数量 /// </summary> public int GroupCount { get => (Source.Count + GroupSize - 1) / GroupSize; } /// <summary> /// List数据源 /// </summary> public List<T> Source { get; set; } public ListGroupIterator() { } public ListGroupIterator(int groupSize) : this(groupSize, null) { } public ListGroupIterator(List<T> list) : this(1, list) { } public ListGroupIterator(int groupSize, List<T> list) { this.GroupSize = groupSize; this.Source = list; } /// <summary> /// ListGroupIterator迭代器 /// </summary> /// <returns></returns> public IEnumerator<List<T>> GetEnumerator() { if (Source?.Count > 0) { var ps = Convert.ToInt32(Math.Ceiling(Source.Count * 1.0d / GroupSize)); var model = Source.Count % GroupSize; for (int i = 0; i < ps; i++) { var len = ps - i == 1 && model > 0 ? model : GroupSize; yield return Source.GetRange(GroupSize * i, len); } } } /// <summary> /// 将List<T>实例赋值给ListGroupIterator对象 /// </summary> /// <param name="list"></param> public static implicit operator ListGroupIterator<T>(List<T> list) { return new ListGroupIterator<T> { Source = list }; } } }
调用
using System; using System.Collections.Generic; namespace Demo { class Program { static void Main() { ListGroupIterator<int> lg1 = new List<int>() { 1, 2, 3, 4, 5 }; ListGroupIterator<int> lg2 = new ListGroupIterator<int>(new List<int> { 1, 2, 3, 4, 5 }); ListGroupIterator<int> lg3 = new ListGroupIterator<int>(3, new List<int>() { 1, 2, 3, 4, 5 }); lg3.Source.AddRange(new List<int>() { 6, 7, 8, 9 }); lg3.GroupSize = 2; foreach (var item in lg3) { Console.WriteLine(string.Join(",", item)); } Console.ReadLine(); } } }
The Times 03/Jan/2009 Chancellor on brink of second bailout for banks
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性