前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#将 List 转为 byte[]

C#将 List 转为 byte[]

作者头像
zls365
发布2020-08-19 11:07:18
2.5K0
发布2020-08-19 11:07:18
举报
文章被收录于专栏:CSharp编程大全CSharp编程大全
代码语言:javascript
复制
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;

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-09-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 CSharp编程大全 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档