开发者

Lambda Expression Example [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current开发者_StackOverflow社区 form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜