C#字节数组的合并,取子数组操作.哪种写法的性能最好

2025-03-11 07:15:54
推荐回答(1个)
回答1:

一个实例程序,程序中使用的全部是静态扩展方法完成合并、抽取子数组

静态扩展方法本质上是静态方法,完成合并或抽取子数组操作性能最佳。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] b1 = { 1, 2, 3, 4 };
            byte[] b2 = { 5, 6, 7, 8, 9 };
            //数组合并 b ={1,2,3,4,5,6,7,8,9}
            byte[] b = b1.Concat(b2).ToArray();
            
            //抽取子数组,以抽取偶数为例
            byte[] c = b.Where(x => x % 2 == 0).ToArray();
                       
            //抽取子数组,以抽取奇数为例
            byte[] d = b.Where(x => x % 2 == 1).ToArray();
                       
            //抽取子数组,以抽取小于5的数
            byte[] f = b.Where(x => x < 5).ToArray();
        }
    }
}