如何使用C#通过其ID更新ObservableCollection?
我有一个像这样的自定义对象的可观察集合如何使用C#通过其ID更新ObservableCollection?,c#,linq,c#-4.0,lambda,observablecollection,C#,Linq,C# 4.0,Lambda,Observablecollection,我有一个像这样的自定义对象的可观察集合 public class Employee() { public int id { get; set; } public decimal salary { get; set; } } ObservableCollection<Employee> employeeCollection = new ObservableCollection<Employee>() { new Employee() { id =
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 }
};
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 }
}
public class Employee()
{
公共int id{get;set;}
公共十进制工资{get;set;}
}
ObservableCollection employeeCollection=新的ObservableCollection()
{
新员工(){id=1,工资=1000.00},
新员工(){id=2,工资=1500.00},
新员工(){id=3,工资=2000.00},
新员工(){id=4,工资=2500.00},
新员工(){id=5,工资=3000.00}
};
id是此集合中的唯一属性。如何根据id更新集合的薪资,并以最有效的方式获取整个集合
i、 e:如果我将id为3的员工的工资更新为5000.00,结果需要如下
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 }
};
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 }
}
employeeCollection=新的ObservableCollection()
{
新员工(){id=1,工资=1000.00},
新员工(){id=2,工资=1500.00},
新员工(){id=3,工资=5000.00},
新员工(){id=4,工资=2500.00},
新员工(){id=5,工资=3000.00}
}
我需要用更新的值获取整个集合
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
或
我个人不喜欢第二种方法
其他资源 返回序列的第一个元素,如果找不到元素,则返回默认值
如果您知道集合中已存在具有所需id的员工,则只需执行(使用Linq)
employeeCollection.Where(e=>e.id==requiredID).First().salary=newSalary代码>如果不确定是否存在具有所需id的员工,您可能需要分两步进行(1.检查并找到该员工。2a.如果找到,设置工资。2b.如果未找到,根据您的需要处理情况…@elgonzo无需使用Where
语句,只需将选择标准移动到第一个(…)
@MikeH,你是对的。不记得First
也接受谓词。智能感知会腐蚀我的大脑;-)OP表示ID是唯一的…可能是带有空检查的first或default
?谢谢@The General你救了我的命