一个大数组根据特定大小分割为多个小数组

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

复制代码

 

posted @   LearningAlbum  阅读(171)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
点击右上角即可分享
微信分享提示