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 @ 2023-02-09 17:54 LearningAlbum 阅读(171) 评论(0) 推荐(0) 编辑
摘要: 以前觉得虚拟机稳定点,操作简单,就没有把虚拟机的服务迁移到docker,随着对docker的理解,觉得还是这种进程级的虚拟环境干净,轻量级。先拿Gitlab来做个列子迁移 要想Gitlab的数据能持久的保存,备份,还原,所以必须能把数据挂载到windows的目录下,docker下执行, 端口映射第一 阅读全文
posted @ 2022-08-07 01:22 LearningAlbum 阅读(928) 评论(0) 推荐(0) 编辑
摘要: 项目中需要用到性能测试,发现.net 平台的这个神器. 觉得很不错,接下来准备做个系列。具体参考官方介绍 做基线对比测试不是那么容易,你很容易就翻车掉坑里,BenchmarkDotNet 会帮你避坑(即使你是老司机),它会帮你干很多体力活,比如它会针对每个benchmark方法生成独立的工程项目,并 阅读全文
posted @ 2020-01-12 17:40 LearningAlbum 阅读(2479) 评论(2) 推荐(2) 编辑
摘要: 定冠词The 来源于 that/those (那个) 有指代具体哪一个的意思 专有名词只有一个可以理解不加The,那么独一无二的太阳Sun moon为什么加The ? 语法俱乐部里面有详细的解释:类似于“the Great Wall”“the sun”的复合词解释为“那个很great的wall”、“ 阅读全文
posted @ 2019-12-05 22:55 LearningAlbum 阅读(224) 评论(0) 推荐(0) 编辑
点击右上角即可分享
微信分享提示