📅  最后修改于: 2023-12-03 14:39:44.171000             🧑  作者: Mango
In C#, we can easily sum up the values of objects by using LINQ's Sum()
method. This method takes a lambda expression that specifies the property to sum. Here's an example:
List<Employee> employees = new List<Employee>
{
new Employee { Name = "John", Salary = 50000 },
new Employee { Name = "Mary", Salary = 60000 },
new Employee { Name = "Bob", Salary = 40000 }
};
var totalSalary = employees.Sum(e => e.Salary);
Console.WriteLine("Total Salary: " + totalSalary);
This code creates a list of Employee
objects and assigns it to a variable called employees
. It then uses the Sum()
method to sum up the Salary
property of each Employee
object in the list. Finally, it prints out the total salary.
In this example, we're using a lambda expression as the argument to the Sum()
method. The lambda expression specifies which property to sum, in this case Salary
. If our Employee
class had a different property we wanted to sum, we could simply change the lambda expression to reference that property instead.
Here's the Employee
class used in this example:
public class Employee
{
public string Name { get; set; }
public int Salary { get; set; }
}
As you can see, it's a very simple class with just two properties: Name
and Salary
.
In conclusion, the Sum()
method in C# makes it easy and straightforward to sum up values of objects. With just a few lines of code, we can sum up any property we want using a lambda expression.