Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace for-loops with a functional statement in C#?

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?
like image 490
Lernkurve Avatar asked Apr 15 '10 16:04

Lernkurve


People also ask

Are for loops allowed in functional programming?

Bookmark this question. Show activity on this post. We dont use for loop in functional programming, instead, we use higher order functions like map, filter, reduce etc. These are fine for iterating through an array.

What can we use instead of for loop in C#?

C# foreach loop is used to iterate through items in collections (Lists, Arrays etc.). When you have a list of items, instead of using a for loop and iterate over the list using its index, you can directly access each element in the list using a foreach loop.

How do you replace a loop?

Map() Function in Python The map() function is a replacement to a for a loop. It applies a function for each element of an iterable.

Can you replace a while loop with a for loop?

for() loop can always be replaced with while() loop, but sometimes, you cannot use for() loop and while() loop must be used.


1 Answers

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]; } 
like image 116
dtb Avatar answered Sep 21 '22 23:09

dtb