如何用C#中的函数语句替换for循环? [英] How to replace for-loops with a functional statement in C#?
问题描述
当问及如何避免for循环时,他的回答是使用功能语言。但是,如果你被一个非功能性语言卡住了,比如C#,那么有什么技术可以避免for-loops或者通过重构来摆脱它们呢?用lambda表达式和LINQ也许?如果是这样,怎么做?
问题 所以问题归结为: 功能结构往往比for循环更清楚地表达你的意图,数据集并希望转换,过滤或聚合元素。 当您想要重复执行某些操作时,循环非常合适。 更明确地表达您的意图 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:
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 much more clearly expresses your intent than
这篇关于如何用C#中的函数语句替换for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b $ p例如
int x = array.Sum( );
int x = 0;
for(int i = 0; i< array.Length; i ++)
{
x + = array [i];
}
int x = array.Sum();
int x = 0;
for (int i = 0; i < array.Length; i++)
{
x += array[i];
}