如何用C#中的函数语句替换for循环? [英] How to replace for-loops with a functional statement in C#?

查看:256
本文介绍了如何用C#中的函数语句替换for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一位同事曾经说过,每当我写一个for循环的时候,上帝正在杀死一只小猫。

当问及如何避免for循环时,他的回答是使用功能语言。但是,如果你被一个非功能性语言卡住了,比如C#,那么有什么技术可以避免for-loops或者通过重构来摆脱它们呢?用lambda表达式和LINQ也许?如果是这样,怎么做?



问题

所以问题归结为:


  1. 为什么for循环不好?或者,在什么情况下for循环避免,为什么?
  2. 你可以提供C#代码的例子,它看起来如何之前,即循环,然后没有循环? li>


解决方案

功能结构往往比for循环更清楚地表达你的意图,数据集并希望转换,过滤或聚合元素。

当您想要重复执行某些操作时,循环非常合适。


$ b $ p例如

  int x = array.Sum( ); 

更明确地表达您的意图

  int x = 0; 
for(int i = 0; i< array.Length; i ++)
{
x + = array [i];
}


A colleague once said that God is killing a kitten every time I write a for-loop.

When asked how to avoid for-loops, his answer was to use a functional language. However, if you are stuck with a non-functional language, say C#, what techniques are there to avoid for-loops or to get rid of them by refactoring? With lambda expressions and LINQ perhaps? If so, how?

Questions

So the question boils down to:

  1. Why are for-loops bad? Or, in what context are for-loops to avoid and why?
  2. Can you provide C# code examples of how it looks before, i.e. with a loop, and afterwards without a loop?

解决方案

Functional constructs often express your intent more clearly than for-loops in cases where you operate on some data set and want to transform, filter or aggregate the elements.

Loops are very appropriate when you want to repeatedly execute some action.


For example

int x = array.Sum();

much more clearly expresses your intent than

int x = 0;
for (int i = 0; i < array.Length; i++)
{
    x += array[i];
}

这篇关于如何用C#中的函数语句替换for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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