一个大数组根据特定大小分割为多个小数组
1. Using Skip()
and Take() 的普通方法(效率更高,linq需要迭代每个元素)
using System; using System.Linq; using System.Collections.Generic; public static class Extensions { public static IEnumerable<IEnumerable<T>> Split<T>(this T[] arr, int size) { for (var i = 0; i < arr.Length / size + 1; i++) { yield return arr.Skip(i * size).Take(size); } } } public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int size = 2; var arrays = arr.Split(size); foreach (var array in arrays) { Console.WriteLine(String.Join(", ", array)); } } }
2. Using Skip()
and Take() 的Linq select
using System; using System.Linq; using System.Collections.Generic; public static class Extensions { public static IEnumerable<IEnumerable<T>> Split<T>(this T[] arr, int size) { return arr.Select((s, i) => arr.Skip(i * size).Take(size)).Where(a => a.Any()); } } public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int size = 2; var arrays = arr.Split(size); foreach (var array in arrays) { Console.WriteLine(String.Join(", ", array)); } } }
3. Using Enumerable.GroupBy
Method
using System; using System.Linq; public class Example { public static void Main() { int[] arr = { 1, 2, 3, 4, 5 }; int size = 2; int i = 0; int[][] arrays = arr.GroupBy(s => i++ / size).Select(s => s.ToArray()).ToArray(); foreach (var array in arrays) { Console.WriteLine(String.Join(", ", array)); } } }
具体迭代过程是这样,我们常规的GroupBy是迭代元素的属性参加分组结果,比如按照每个同学的班主任分组,这里迭代元素s本身没有参与分组属性,而是借助了外部的一个变量i来生成评判结果,用这个结果来对所迭代的元素分组
s->1 i=0 i++/2 = 0
s->2 i=1 i++/2 = 0
s->3 i=2 i++/2 = 1
s->4 i=3 i++/2 = 1
s->5 i=4 i++/2 = 2
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性