Question

In WPF, I want to display sum, average values based on the List of Items provided.

For example, I have an Employee object with Salary Property, and I want to calculate total salary based on the employee list. Also, the employee object is data bound to a Items control where the Salary will be edited/new Employee may be added to the list.

Can anyone provide me a solution to achieve this?

Was it helpful?

Solution

I would do this:

In your code behind or ViewModel (if your using MVVM) create a new dependency property called AverageSalary.

Then change Salary on the employee to also be a dependency property. In the code behind you can then listen to when the Employee.Salary changes. (see this link for details on that) And when it changes recompute the average like listed above then assign it to the AverageSalary dependency property you created.

Then just bind your UI to the AverageSalary property and it should update as the employee's salaries change.

OTHER TIPS

Using LINQ, you can simply do something along the lines of

var averageSalary = yourEmployeeList.Average(employee => employee.Salary);

Same holds true for the Sum.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top