1. Using Skip()
and Take() 的普通方法
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)); } } }
标签:分割,int,arr,System,特定,数组,using,public,size From: https://www.cnblogs.com/deepinnet/p/17106549.html