【问题标题】:How can I update ObservableCollection by its ID using C#?如何使用 C# 通过其 ID 更新 ObservableCollection?
【发布时间】: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 =&gt; e.id == requiredID).First().salary = newSalary; 如果不确定是否存在具有所需 id 的员工,您可能需要分两步来解决(1.检查并找到员工。2a。如果找到,设置工资。2b。如果没有找到,根据您的需要处理情况......)
  • @elgonzo 不需要Where 语句,只需将选择条件移到First(...) 中即可
  • @MikeH,你是对的。不记得First 也接受谓词。 Intellisense 腐蚀了我的大脑 ;-)

标签: c# linq c#-4.0 lambda observablecollection


【解决方案1】:
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

返回序列的第一个元素,如果没有找到元素,则返回默认值。

【讨论】:

  • OP 表明 ID 是唯一的......也许是带有空检查的 FirstOrDefault
  • 谢谢@TheGeneral,你救了我的命
猜你喜欢
  • 2023-03-31
  • 2011-01-06
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
相关资源
最近更新 更多