C# list常用的几个操作 改变list中某个元素的值 替换某一段数据

时间:2025-04-01 18:09:48

 

1、改变list中某个元素的值

    public class tb_SensorRecordModel
    {
        public int ID { get; set; }
        public decimal Value1 { get; set; }
    }
            List<tb_SensorRecordModel> list = new List<tb_SensorRecordModel>();
            (new tb_SensorRecordModel { ID = 1, Value1 = 1 });
            (new tb_SensorRecordModel { ID = 2, Value1 = 2 });
            (new tb_SensorRecordModel { ID = 3, Value1 = 3 });

            //改变list中某个元素值
            var model = (c =>  == 2).FirstOrDefault();
            model.Value1 = 2222;

            (c =>
            {
                //打印的数据表明 list中的那个元素 确实被改变了
                //知识:引用、地址
                ($"{},{c.Value1}");
            });
            ();
            return;

 

 

2、替换某一段数据

            List<tb_SensorRecordModel> list1 = new List<tb_SensorRecordModel>();
            (new tb_SensorRecordModel { ID = 1, Value1 = 1 });
            (new tb_SensorRecordModel { ID = 2, Value1 = 2 });
            (new tb_SensorRecordModel { ID = 3, Value1 = 3 });
            (new tb_SensorRecordModel { ID = 4, Value1 = 4 });
            (new tb_SensorRecordModel { ID = 5, Value1 = 5 });

            //构造新的一段数据
            List<tb_SensorRecordModel> list2 = new List<tb_SensorRecordModel>();
            (new tb_SensorRecordModel { ID = 2, Value1 = 2222 });
            (new tb_SensorRecordModel { ID = 3, Value1 = 3333 });

            //删除 旧的 那段数据
            (1, 2);

            //将新的 这段数据 插入到 指定位置
            (1, list2);

            (c =>
            {
                ($"{},{c.Value1}");
            });
            ();
            return;