环境:vs2003 winform程序,
  有一个savelist,里面装的每一个对象都是byte[20],我想把savelist中所有的对象取出来,存到一个
  byte[20*list.Count]中去,有什么好办法?下面是我写的代码, 可以实现该功能,但比较麻烦,用到 一个临时数组,还要用到两层的for循环,有没有高手指点一下,弄个更好的方法.
        public ArrayList saveList = new ArrayList ( );
        int count = saveList.Count;    //记录有多少个20个字节的包
byte[] arraybyte= new byte[ 20*count ];

for ( i=0;i < count;i++)
{
byte[] tempa = new byte[20];
tempa = (byte[])saveList[i];
for( j =0;j<20;j++)
{
arraybyte[i*20+j] = tempa[j];
}
}

解决方案 »

  1.   

    没有必要用临时的byte[]吧,
    int index =0;
    foreach(object o in list)
    {
       byte[] array = (byte[]) o;
       // you process
       for(int i = 0; i < array.length; ++i)
       {arraybyte[index] = array[i];
    ++index;
       }
       
    }
      

  2.   

    ArrayList.CopyTo(Array);
    ArrayList有个CopyTo的方法,可以把其里面的数据拷贝到数组.
    如:
    ArrayList al = new ArrayList();
    al.Add("a");//可以是对象
    al.Add("b");string[] arra = new String[al.Count];
    al.CopyTo(arra);
    //那么这就将al数据拷贝到arra中了。
    -----------------------
    www.notsoft.cn
      

  3.   

    序列化,但是需要arraylist中的对象允许序列化
      

  4.   

    ArrayList.CopyTo(Array);
    但它进行复制时是怎么复制的呢??我认为不还是一个一个的吗??
    代码简单了...呵呵
      

  5.   

    byte[] b1 = new byte[]{1,2,3};
    byte[] b2 = new byte[]{4,5,6}; ArrayList list = new ArrayList();
    list.AddRange(b1);
    list.AddRange(b2); byte[] rerultBytes = new byte[list.Count];
    list.CopyTo(rerultBytes);
      

  6.   


    To:mythofcynthia(Blue) 
    foreach(object o in list) 内容临时数组用不用都是可以的,主要是希望效率更高一些,saveList里起码有10万以上的对象(每个对象是一个byte[20]),用foreach 与 用普通的for
    循环相比哪个效率更好些呢?To:lovvver(EBright软件) ( )
    恩,我也想过用Copyto 预想用其本身自带的函数也许会更快一些,难点在于里面的是byte[20]的对象,而这边是个字节数组而已,类型是不一样的,放到byte里是要用的,要不你取出来还是一个byte[20]的对象,就还得转化,画的时间将更长,
    用CopyTo是否效率更高一些,大家一起来学习,呵呵
      

  7.   

    用Buffer.BlockCopy()吧,如果是byte[]的话,这个应该是效率比较高了
      

  8.   

    To:mythofcynthia(Blue) 
    请兄弟您根据要求,将代码帖出来大家分析一下好吗?我没接触过这东西
      

  9.   

    byte[] arraybyte= new byte[ 20*count ];
    int index = 0;
    foreach(object o in list)
    {
       //System.Buffer.BlockCopy(src, srcOffset, dst, dstOffset, count);
       system.buffer.BlockCopy((byte[])o, 0, arraybyte, index * 20, 20);
       ++index;
    }
      

  10.   

    mythofcynthia(Blue)  的作法我才了,这样的算法,在每个对象的byte比较多时,效率是比较高的,如每个对象都是byte[1000]时,
    lovvver(EBright软件)的做法我其实也考虑过,效率有待验证.