Foreach vs lambda表达式 [英] Foreach vs lambda expression

查看:255
本文介绍了Foreach vs lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个人员类型列表。人员类型有两个属性。姓名和年龄。当然,Name是字符串类型,Age是int类型。



现在我想将2乘以Age of all。



所以我想使用foreach循环,每个项目乘以2.



另一种选择是使用lambda表达式。

I have a list of People type. The people type has two properties. Name and Age. Of course, Name is string type and Age is int type.

Now I want to multiply 2 to the Age of all.

So I want to use foreach loop, each item times 2.

The other option is to use lambda expression.

return list.(x=>x*2);





哪种方式更好?



我尝试了什么:



我被专家告知。答案是使用lamada表达式而不是foreach循环。

但我仍然没有找到支持它的强大理由。



Which way is better?

What I have tried:

I was advised by an "expert". The answer was to use lamada expression rather than foreach loop.
But I still have not found a strong reason to support it.

推荐答案

这取决于。



这是性能比较:

It depends.

Here is a performance comparison:
class Program
{
    static void Main(string[] args)
    {
        var persons = new List<Person>();
        for (int i = 0; i < 10000; i++)
        {
            persons.Add(new Person { Name =


person {i},age = i});
}

var sw = new 秒表();

sw.Start();
for int i = 0 ; i < 1000 ; i ++)
{
for int j = 0 ; j < 10000 ; j ++)
{
人[j] .age ++;
}
}
sw.Stop();
Console.WriteLine(
"person {i}", age = i }); } var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000; i++) { for (int j = 0; j < 10000; j++) { persons[j].age ++; } } sw.Stop(); Console.WriteLine(


for循环:{sw。 ElapsedMilliseconds} ms);

sw.Reset();
sw.Start();
for int i = 0 ; i < 1000 ; i ++)
{
foreach var person in persons)
{
person.age ++;
}
}
sw.Stop();
Console.WriteLine(
"for loop: {sw.ElapsedMilliseconds} ms"); sw.Reset(); sw.Start(); for (int i = 0; i < 1000; i++) { foreach (var person in persons) { person.age++; } } sw.Stop(); Console.WriteLine(


这篇关于Foreach vs lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆