DEV Community

Ulisses Cavalcante
Ulisses Cavalcante

Posted on

C# lambda vs foreach readability.

Hey guys, recently a receive an feedback that i need to change my code, turn an lambda expression into a foreach loop because its more adherent to clean code, i create this example to explain.
Overall code example

The both versions give me same results, but in my opinion this lambda expression is easy to understand, and easy to write and maintain, and i like to use that.


i receive an recommendation to change that to a for-each loop, like this, to be more clean code adherent.


I really want see other people opinions and arguments about this, and i like lambda expression for me they are very powerful and easy to use.

Top comments (5)

klawingco profile image
Marc Lawingco

I don't understand,
LINQ is much more readable than for each in anyday.
While foreach is faster than LINQ, its not that noticeable enough.

So the idea is
You want readability over performance = LINQ
You want a slightly faster performance over readiblity = For Each.

ucavalcante profile image
Ulisses Cavalcante

Totally agree, ty.

gruenwaldt profile image
Michael Grünwaldt

since you asked for opinions.

For me the linq statement Is much easier to understand. Clear structure and short.

When one is used to linq i don‘t know how to write it clearer.
Even when not used to linq it is almost a sentence.

For me, in this case definately pro linq!

ucavalcante profile image
Ulisses Cavalcante

Ty for your opinion Michael.

ucavalcante profile image
Ulisses Cavalcante

Here an great article about.


Head over to your dashboard

See your total reactions, views, and listings.