user10606387
user10606387

Reputation:

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?

i.e: 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.

Upvotes: 1

Views: 600

Answers (1)

TheGeneral
TheGeneral

Reputation: 81543

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 approach


Additional Resources

Enumerable.FirstOrDefault Method

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

Upvotes: 2

Related Questions