c#用lambda修改符合条件对象的某个字段的三种方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class User 2 { 3 public User(int id, string name, string sex, int age,string address) 4 { 5 this.ID = id; 6 this.Name = name; 7 this.Sex = sex; 8 this.Age = age; 9 this.Address = address; 10 } 11 public User() { 12 13 } 14 public int ID { get; set; } 15 public string Name { get; set; } 16 public string Sex { get; set; } 17 public int Age { get; set; } 18 public string Address { get; set; } 19 20 public List<User> CreateData() { 21 List<User> list =new List<User>{ 22 new User(1, "虞姬", "女", 18, "闸北区"), 23 new User(2, "李白", "男", 22, "静安区"), 24 new User(3, "王昭君", "女", 19, "浦东新区"), 25 new User(4, "后裔", "男", 33, "普陀区"), 26 new User(5, "黄忠", "男", 36, "闸北区"), 27 new User(6, "阿珂", "女", 66, "湖南"), 28 new User(7, "钟无艳", "女", 46, "青浦区") , 29 new User(8, "钟馗", "男", 80, "崇明") , 30 }; 31 return list; 32 } 33 }
以上是测试功能用的基础数据。我要将数据列表中姓钟的英雄的年龄改成99。以下列了三种方法。传统的for 循环就不写出来了
1 //将数据源中姓钟的,并将他的年龄改成99岁 2 List<User> usersss =( from u in userlist 3 select u).ToList(); 4 //方法一: 5 usersss = usersss.Select(o => 6 { 7 o.Age = o.Name.StartsWith("钟") ? 99 : o.Age; 8 return o; 9 }).ToList(); 10 11 //方法二: 12 //usersss.ForEach(o => 13 //{ 14 // o.Age = o.Name.StartsWith("钟") ? 99 : o.Age; 15 //}); 16 17 18 //方法三 19 //usersss = usersss.FindAll(delegate(User o) 20 //{ 21 //if (o.Name.StartsWith("钟")) 22 //{ 23 //o.Age = 99; 24 //} 25 //return o.Name != null; 26 //});