按字节数组排序(字节是long var类型的表示)

时间:2012-07-16 03:22:16

标签: c# serialization binary bytearray deserialization

我有List<byte[]>。每个字节数组的大小为16字节。前8个字节是C#long数据类型的二进制表示,我用它来停止DateTimeTicks。我想知道是否有一种方法可以按照相同的顺序对一堆字节数组进行排序,就像我按升序排序的长等价物一样。显然,如果将每个字节数组反序列化为long然后排序,那么它是否容易,但有没有办法在没有反序列化的情况下逃脱?如果不是,就可以找到将DateTimeTick值转换为二进制表示的逻辑,以便可以直接对二进制执行排序,例如首先以二进制形式表示年份,然后是月,日,小时,分钟,第二,毫秒,..?我的目标是跳过反序列化步骤,因为我需要以二进制格式通过消息传递网络发送已排序的字节数组,并且它目前浪费了大量资源,必须首先反序列化以进行排序(在发送对象之前必须进行排序)通过电线),然后再次序列化它以通过消息传递系统发送它,然后再次反序列化它。

非常欢迎任何想法,提示或解决方案,谢谢。

编辑:我目前使用Linq OrderBy函数对哪个进行快速排序以达到我的目的,并按照这些方式进行排序,性能明智。我想坚持使用Linq,除非不能按字节数组排序,即使我提供了IComparer ......

1 个答案:

答案 0 :(得分:2)

        var rnd = new Random();

        var data = new List<byte[]>();

        //As long as the first 8 bytes are the long, the byte[] can be as long as you want.
        for (int i = 0; i < 10; i++)
            data.Add(BitConverter.GetBytes((ulong)rnd.Next()));

        //Without any 'deserialisation'
        if (BitConverter.IsLittleEndian)
            data = data.OrderBy(x => x[7]).ThenBy(x => x[6]).ThenBy(x => x[5]).ThenBy(x => x[4]).ThenBy(x => x[3]).ThenBy(x => x[2]).ThenBy(x => x[1]).ThenBy(x => x[0]).ToList();
        else  //untested, probably wrong
            data = data.OrderBy(x => x[0]).ThenBy(x => x[1]).ThenBy(x => x[2]).ThenBy(x => x[3]).ThenBy(x => x[4]).ThenBy(x => x[5]).ThenBy(x => x[6]).ThenBy(x => x[7]).ToList();

        //How I'd actually approach it due to simplicity.
        //data = data.OrderBy(x => BitConverter.ToUInt64(x, 0)).ToList();

        data.ForEach(x => Console.WriteLine(BitConverter.ToUInt64(x, 0)));

        Console.ReadLine();

        //There are other approaches of course, but at the fundamental level you're 
        //either going to 'deserialize' the long or test each byte in order.