我有 ObservableCollection <> 这样的自定义对象
public class Employee()
{
public int id { get; set; }
public decimal salary { get; set; }
}
ObservableCollection<Employee> employeeCollection = new ObservableCollection<Employee>()
{
new Employee() { id = 1, salary = 1000.00 },
new Employee() { id = 2, salary = 1500.00 },
new Employee() { id = 3, salary = 2000.00 },
new Employee() { id = 4, salary = 2500.00 },
new Employee() { id = 5, salary = 3000.00 }
};
id是此集合中的唯一属性。如何根据ID更新收款人的薪水,并以最有效的方式获取整个收款人?
即:如果我将ID为3的员工的薪水更新为5000.00,则结果必须是这样
employeeCollection = new ObservableCollection<Employee>()
{
new Employee() { id = 1, salary = 1000.00 },
new Employee() { id = 2, salary = 1500.00 },
new Employee() { id = 3, salary = 5000.00 },
new Employee() { id = 4, salary = 2500.00 },
new Employee() { id = 5, salary = 3000.00 }
}
我需要使用更新后的值来获取整个集合。
答案 0 :(得分:3)
var emp = employeeCollection.FirstOrDefault(x => x.Id == 3)
if(emp != null) // might not exist
emp.salary = 5000
如果您需要处理一组记录
var results = employeeCollection.Where(x => x.Id == 3)
foreach(var emp in results)
emp.salary = 5000
或
employeeCollection.Where(x => x.Id == 3)
.ToList()
.ForEach(x => x.salary = 5000);
我个人不喜欢第二种方法 h
其他资源
Enumerable.FirstOrDefault Method
返回序列的第一个元素,如果未找到任何元素,则返回默认值。