C#將 List 轉爲 byte[]

若是須要查看更多文章,請微信搜索公衆號 csharp編程大全,須要進C#交流羣羣請加微信z438679770,備註進羣, 我邀請你進羣! ! !編程

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;


namespace list
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //將List<double> 轉爲 byte[]
        static byte[] ConvertDoubleArrayToBytes(List<double> matrix)
        {
            if (matrix == null)
            {
                return new byte[0];
            }
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryWriter bw = new BinaryWriter(stream);
                foreach (var item in matrix)
                {
                    bw.Write(item);
                }
                return stream.ToArray();
            }
        }
        //將byte[] 轉爲 List<double>
        static List<double> ConvertBytesToDoubleArray(byte[] matrix)
        {
            if (matrix == null)
                return null;

            List<double> result = new List<double>();
            using (var br = new BinaryReader(new MemoryStream(matrix)))
            {
                var ptCount = matrix.Length / 8;
                for (int i = 0; i < ptCount; i++)
                {
                    result.Add(br.ReadDouble());
                }
                return result;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<double> data = new List<double> { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 };
            byte[] bdata = ConvertDoubleArrayToBytes(data);
            data = ConvertBytesToDoubleArray(bdata);
            foreach (var item in data)
            {
                listBox1.Items.Add(item);
            }
           

        }
    }
}

  

 

 

List<T>是泛型集合
這種集合規定了集合內的數據類型,只能存放<T>的T類型數據;
而ArrayList不是泛型,這種集合中能夠存聽任意類型數據;
舉個簡單例子:List<Student> students=new List<Student>(); 那麼讀取數據時就不用類型轉化了,即:Student stu=students[0]; 增、刪、改、查的方法:students.Add(T t);//增 students.Remove(int index);//刪 stucents.Remove(T t);//刪 students[]=//修改的數據 //查或者改 遍歷集合相似於遍歷數組 ArrayList students=new ArrayList(); Student stu=students[0] as Student;數組

相關文章
相關標籤/搜索