Calculate sum , average based on list of items in WPF

两盒软妹~` 提交于 2019-12-13 20:05:25

问题


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?


回答1:


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.




回答2:


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

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

Same holds true for the Sum.



来源:https://stackoverflow.com/questions/3810188/calculate-sum-average-based-on-list-of-items-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!