Ciao everyone,
i was finally able to switch from .NET Framework 2.0 to .NET Framework 4.0.
I am trying to get some experience about lambda expression and LINQ.
Is it possible to translate this:
for (int cont = 0;cont < args.Length; cont++)
Console.WriteLine("#" + cont + " " + "<" + args + ">");
into a single line lambda expression,or using LINQ, or even some other costruct i am no aware of ?
Thank you in advance.
LINQ operations shouldn’t have side effects or do actions. They should only be used to produce, from a
IEnumerable<T>anotherIEnumerable<T>(or from aIQueryable<T>anotherIQueryable<T>orIEnumerable<T>) (or if aggregating, like.Max,.All… a single result)Read for example http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx.
(and note that this question is quite asked on SO… Read for example my reply here ToList().ForEach in Linq and see a solution to a similar problem)
Now, if you hate yourself enough, you can do this:
We are using the
.All(p => p)to “materialize” theSelectoperation. This becauseSelectis “lazy” and won’t be executed if no one cycles it.Technically you could even try to obfuscate it a little:
(
Allchecks that all the elements aretrueand stops if one of the isfalse, so it has to cycle all of them (because we alwaysreturn true;).Any(as written) checks that at least one of the elements istrueand then stops (but all of our elements arefalse, becasue we doreturn false;so theAnywill cycle all the elements)Now… The advantage of these techniques over using
ToListis that we aren’t “duplicating” anArrayto aList<T>just to use a “wrong” method ofList<T>. If theForEachmethod ofList<T>is “wrong”, duplicating anArrayto aListjust to use it is doubly-wrong.