C# list經常使用的幾個操做 改變list中某個元素的值 替換某一段數據

 

一、改變list中某個元素的值spa

public class tb_SensorRecordModel { public int ID { get; set; } public decimal Value1 { get; set; } }
List<tb_SensorRecordModel> list = new List<tb_SensorRecordModel>(); list.Add(new tb_SensorRecordModel { ID = 1, Value1 = 1 }); list.Add(new tb_SensorRecordModel { ID = 2, Value1 = 2 }); list.Add(new tb_SensorRecordModel { ID = 3, Value1 = 3 }); //改變list中某個元素值
            var model = list.Where(c => c.ID == 2).FirstOrDefault(); model.Value1 = 2222; list.ForEach(c => { //打印的數據代表 list中的那個元素 確實被改變了 //知識:引用、地址
                Console.WriteLine($"{c.ID},{c.Value1}"); }); Console.Read(); return;

 

 

二、替換某一段數據code

List<tb_SensorRecordModel> list1 = new List<tb_SensorRecordModel>(); list1.Add(new tb_SensorRecordModel { ID = 1, Value1 = 1 }); list1.Add(new tb_SensorRecordModel { ID = 2, Value1 = 2 }); list1.Add(new tb_SensorRecordModel { ID = 3, Value1 = 3 }); list1.Add(new tb_SensorRecordModel { ID = 4, Value1 = 4 }); list1.Add(new tb_SensorRecordModel { ID = 5, Value1 = 5 }); //構造新的一段數據
            List<tb_SensorRecordModel> list2 = new List<tb_SensorRecordModel>(); list2.Add(new tb_SensorRecordModel { ID = 2, Value1 = 2222 }); list2.Add(new tb_SensorRecordModel { ID = 3, Value1 = 3333 }); //刪除 舊的 那段數據
            list1.RemoveRange(1, 2); //將新的 這段數據 插入到 指定位置
            list1.InsertRange(1, list2); list1.ForEach(c => { Console.WriteLine($"{c.ID},{c.Value1}"); }); Console.Read(); return;
相關文章
相關標籤/搜索