一个大数组根据特定大小分割为多个小数组
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