简体   繁体   中英

How can I update ObservableCollection by its ID using C#?

I have an ObservableCollection<> of custom objects like this

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 is the unique property in this collection. How can I update the collection's salary based on id and get the entire collection in the most efficient way?

ie: If I update the salary to 5000.00 of the employee whose id is 3, the result need to be like this

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 }
}

I need to get the entire collection with the updated values.

var emp = employeeCollection.FirstOrDefault(x => x.Id == 3)
if(emp != null) // might not exist
   emp.salary = 5000

If you need to work with a set of records

var results = employeeCollection.Where(x => x.Id == 3)

foreach(var emp in results)
   emp.salary = 5000

or

employeeCollection.Where(x => x.Id == 3)
                  .ToList()
                  .ForEach(x => x.salary = 5000);

Personally i don't like the second approac h


Additional Resources

Enumerable.FirstOrDefault Method

Returns the first element of a sequence, or a default value if no element is found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM