Lambda 表达式示例

发布于 2024-11-07 21:45:10 字数 64 浏览 0 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

肥爪爪 2024-11-14 21:45:10

让我们看看

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;

lambda

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

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);
难忘№最初的完美 2024-11-14 21:45:10
class Human
{
    public int Age { get; set; }
}

IEnumerable<Human> people = ...
int age = people.Average(p => p.Age);
class Human
{
    public int Age { get; set; }
}

IEnumerable<Human> people = ...
int age = people.Average(p => p.Age);
魂牵梦绕锁你心扉 2024-11-14 21:45:10
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
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文