Lambda表达示例

时间:2011-05-14 15:36:25

标签: c# .net linq lambda

有人能给我看一个计算的“传统”例子,例如找到人们年龄的平均值,使用循环方法,然后使用lambda表达式

3 个答案:

答案 0 :(得分:2)

让我们看看

class People
{
  int Age {get;set;}
};

var people = new List<People>() {...};

方法循环

int sum = 0;
foreach(var p in people)
 sum += p.Age;
int average = sum / people.Count;

的λ

int average = people.Average(p => p.Age);

答案 1 :(得分:1)

class Human
{
    public int Age { get; set; }
}

IEnumerable<Human> people = ...
int age = people.Average(p => p.Age);

答案 2 :(得分:1)

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