【发布时间】:2018-11-12 23:33:11
【问题描述】:
我有一个 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 }
}
我需要使用更新后的值获取整个集合。
【问题讨论】:
-
如果您知道具有所需 id 的员工已经在集合中,那么您可以简单地执行(使用 Linq)
employeeCollection.Where(e => e.id == requiredID).First().salary = newSalary;如果不确定是否存在具有所需 id 的员工,您可能需要分两步来解决(1.检查并找到员工。2a。如果找到,设置工资。2b。如果没有找到,根据您的需要处理情况......) -
@elgonzo 不需要
Where语句,只需将选择条件移到First(...)中即可 -
@MikeH,你是对的。不记得
First也接受谓词。 Intellisense 腐蚀了我的大脑 ;-)
标签: c# linq c#-4.0 lambda observablecollection