Lambda Expression Example [closed]
Could someone show me an "traditional" example of a calculation e.g. find average of peoples age, using a loop method and then an example using a lambda expression
Let's see
class People
{
int Age {get;set;}
};
var people = new List<People>() {...};
method loop
int sum = 0;
foreach(var p in people)
sum += p.Age;
int average = sum / people.Count;
lambda
int average = people.Average(p => p.Age);
class Human
{
public int Age { get; set; }
}
IEnumerable<Human> people = ...
int age = people.Average(p => p.Age);
var ages = new int[] { 10, 12, 14 };
var sum = 0;
var count = 0;
// loop
foreach (var age in ages) {
count++;
sum += age;
}
var average = sum / count;
// lambda
ages.Average(x => x); // this is where it'd be something like x.age if it was an array of objects instead of ints
精彩评论