Lambda Expressions
[Blog Map] [Table of Contents] [Next Topic]
Note: This article is a topic in a much larger tutorial on writing pure functional code in C#. Lambda expressions are only one of the pieces in a much larger puzzle. Functional programming in C# allows us to write shorter programs that perform better, and are much more robust. Query Composition using Functional Programming Techniques explains lambda expressions in their proper context.
This blog is inactive.
New blog: EricWhite.com/blog
Blog TOCIn order to learn functional programming and a more declarative style of writing code, we need first to cover some basic material. One of the first concepts is that of lambda expressions. Lambda expressions can be summarized in one sentence:
Lambda expressions are simply functions/methods.
They have a different syntax, primarily so that they can be written in expression context (more on this shortly) instead of as a member of a class. However, that is all they are. For instance, the following lambda expression:
c => c + 1
is a function that takes one argument, c, and returns the value c + 1.
Actually, they are slightly more complicated than this, but not much more. For the purposes of this tutorial, you only use lambda expressions when calling a method that takes a delegate as a parameter. Instead of writing a method, creating a delegate from the method, and passing the delegate to the method as a parameter, you can simply write a lambda expression in-line as a parameter to the method.
To show lambda expressions in context, consider the problem where you have an array with 10 digits in it, and you want to filter for all digits greater than 5. In this case, you can use the Where extension method, passing a lambda expression as an argument to the Where method:
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
foreach (int i in source.Where(x => x > 5))
Console.WriteLine(i);
To understand the semantics of this code, you needn't find some method elsewhere in the source code that does the selection; the code that you need to read is much tighter and smaller. It reflects your intent in a much cleaner fashion.
Later on in this tutorial, you'll see a number of uses of the standard query operators. Many of the standard query operators, including Where, take delegates as an argument, so this means that we can call them passing a lambda as an argument.
First, a quick review of delegates:
Defining, Creating, and Using a Delegate
In C#, a delegate is a data structure that refers to either a static method, or an object and an instance method of its class. When you initialize a delegate, you initialize it with either a static method, or a class instance and an instance method.
The following code shows the definition of a delegate and a method that can be used to initialize the delegate:
// Defines a delegate that takes an int and returns an int
public delegate int ChangeInt(int x);
// Define a method to which the delegate can point
static public int DoubleIt(int x)
{
return x * 2;
}
Now, you can create and initialize an instance of the delegate, and then call it:
ChangeInt myDelegate = new ChangeInt(DelegateSample.DoubleIt);
Console.WriteLine("{0}", myDelegate(5));
This, as you would expect, writes 10 to the console.
Using an Anonymous Method
With C# 2.0, anonymous methods allow you to write a method and initialize a delegate in place:
ChangeInt myDelegate = new ChangeInt(
delegate(int x)
{
return x * 2;
}
);
Console.WriteLine("{0}", myDelegate(5));
Using a Lambda Expression
With Lambda expressions, the syntax gets even terser:
ChangeInt myDelegate = x => x * 2;
Console.WriteLine("{0}", myDelegate(5));
This lambda expression is an anonymous method that takes one argument x, and returns x * 2. In this case, the type of x and the type that the lambda returns are inferred from the type of the delegate to which the lambda is assigned.
If you wanted to, you could have specified the type of the argument, as follows:
ChangeInt myDelegate = (int x) => x * 2;
Console.WriteLine("{0}", myDelegate(5));
Using a Lambda with Two Arguments
When using the Standard Query Operators, on occasion, you need to write a lambda expression that takes two arguments.
If you have a delegate that takes two arguments:
// Defines a delegate that takes two ints and returns an int
public delegate int MultiplyInts(int arg, int arg2);
You can declare and initialize a delegate:
MultiplyInts myDelegate = (a, b) => a * b;
Console.WriteLine("{0}", myDelegate(5, 2));
Statement Lambda Expressions
You can write a more complicated lambda expression using statements, enclosing the statements in braces. If you use this syntax, you must use the return statement, unless the lambda returns void:
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
foreach (int i in source.Where(
x =>
{
if (x <= 3)
return true;
else if (x >= 7)
return true;
return false;
}
))
Console.WriteLine(i);
Sometimes developers wonder how to pronounce the => token.
If the lambda expression is a predicate, expressing some condition: c => c.State == "WA" then the => can be spoken as "such that". In this example, you could say "c such that c dot state equals Washington". If the lambda expression is a projection, returning a new type: c => new XElement("CustomerID", c.CustomerID); then the => can be spoken as "becomes". In the above example, you could say "c becomes new XElement with a name of CustomerID and its value is c dot CustomerID". Or "maps to", or "evaluate to", as suggested in the comments below. But most often, I just say "arrow". J
A quick note: predicates are simply boolean expressions that are passed to some method that will use the boolean expression to filter something. A lambda expression used for projection takes one type, and returns a different type. More on both of these concepts later.
Lambda Expressions that Return Void
A lambda expression that returns void is not very useful in the context of functional programming because the only possible reason for such a function is that it has side-effects, and is not pure (more on this later in the tutorial), but it is part of C# 3.0 syntax, so I'll cover it here. Sometimes developers will use a void statement lambda expression for writing an event handler. This has the benefit that the syntax is terser, and the program is smaller. In addition, the lambda expression can refer to local variables in the enclosing scope. This is part of C#'s implementation of closures. The only way to write a lambda expression that returns void is to write a statement lambda expression. The following example shows defining a void delegate, declaring an instance of it, and calling it.
// Defines a delegate that takes a string and returns void
public delegate void OutputToConsole(string arg);
static void Main(string[] args)
{
OutputToConsole o = a => {
Console.WriteLine(a);
};
o("Hello, World");
}
If you write a lambda expression for a delegate that returns void and takes no arguments, it results in interesting syntax:
// Defines a delegate that takes no arguments and returns void
public delegate void OutputHelloToConsole();
static void Main(string[] args)
{
OutputHelloToConsole o = () =>
{
Console.WriteLine("Hello, World");
};
o();
}
The Func Delegate Types
The framework defines a number of parameterized delegate types:
public delegate TR Func<TR>();
public delegate TR Func<T0, TR>(T0 a0);
public delegate TR Func<T0, T1, TR>(T0 a0, T1 a1);
public delegate TR Func<T0, T1, T2, TR>(T0 a0, T1 a1, T2 a2);
public delegate TR Func<T0, T1, T2, T3, TR>(T0 a0, T1 a1, T2 a2, T3 a3);
In the above delegate types, notice that if there is only one type parameter, it is the return type of the delegate. If there are two type parameters, the first type parameter is the type of the one and only argument, and the second type is the return type of the delegate, and so on. Many of the standard query operators (which are just methods that you call) take as an argument a delegate of one of these types. These delegate definitions are useful to you when writing your own methods that take a delegate as an argument.
using System;
using System.Collections.Generic;
class Program
{
static List<T> MyWhereMethod<T>(IEnumerable<T> source,
Func<T, bool> predicate)
{
List<T> l = new List<T>();
foreach (T item in source)
if (predicate(item))
l.Add(item);
return l;
}
static void Main(string[] args)
{
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
List<int> filteredList = MyWhereMethod(source,
i => i >= 5);
foreach (int z in filteredList)
Console.WriteLine(z);
}
}
The Action Delegate Types
The framework defines a number of parameterized delegate types for delegates that return void:
public delegate void Action();
public delegate void Action<T0>(T0 a0);
public delegate void Action<T0, T1>(T0 a0, T1 a1);
public delegate void Action<T0, T1, T2>(T0 a0, T1 a1, T2 a2);
public delegate void Action<T0, T1, T2, T3>(T0 a0, T1 a1, T2 a2, T3 a3);
Sometimes API designers will include an event that takes one of these delegate types as an argument, and you can write a lambda expression for the argument. As with the Func delegate types, these delegate definitions are useful to you when writing your own methods that take a delegate as an argument. This uses the interesting syntax of () => { /* body of void function here */ };
using System;
using System.Collections.Generic;
using System.Threading;
class Program
{
static void SomeAsynchronousMethod(Action complete)
{
// just pretending to be asynchronous in this example
Thread.Sleep(1000);
complete();
}
static void Main(string[] args)
{
SomeAsynchronousMethod(() => { Console.WriteLine("Done"); });
}
}
Expression Trees
Lambda expressions can also be used as expression trees. This is an interesting topic, but is not part of this discussion on writing pure functional transformations.
[Blog Map] [Table of Contents] [Next Topic]
Comments
Anonymous
December 08, 2006
Time to continue with the longest running series on C# 3.0. Lambda expressions originated from lambdaAnonymous
March 01, 2007
You've been kicked (a good thing) - Trackback from DotNetKicks.comAnonymous
June 07, 2007
One of the questions I've had about the new lambda expression syntax in C# 3.0 is how to pronounce it...Anonymous
August 10, 2007
Really brief and nice. I like it ! And this article, of course ... :)Anonymous
August 27, 2007
I think that the => operator should be pronounced as "induces", as it does in fommal logics.Anonymous
October 18, 2007
Great article - feels like it's pitched right at me. You could pronounce "=>" as "returning" - it works in both your examples.Anonymous
October 20, 2007
Body: I arrived a bit late in the morning and missed the opening Keynote on Silverlight by Jason ZanderAnonymous
November 30, 2007
Do you want to know what's new in the 3rd version of the lovely C# :) ? just check the links below: ...Anonymous
January 13, 2008
it's a little difficult between telling the difference between this and a normal function call. i think people would be better served if you passed the delegate into a quicksort function for pedagogical purposes.Anonymous
January 19, 2008
Hello there I found this article by searching on google. What can I say, I made some tests regarding Lambda Expressions. One of them is that, for sure, the parameters are still STRONGLY TYPE. Just analyze that : public delegate T SomeDelegate<T> (T A,T B); and then : SomeDelegate<String> calcul = (x, y) => { MessageBox.Show(x.GetType().ToString()); return String.Empty; }; So, the typeof(x) is String, just like the type value that was passed for the "SomeDelegate<T>". There are much more things interesting regarding Lambda Expressions. I used them most of all in custom Extention Methods.Anonymous
January 19, 2008
Or... try that : MessageBox.Show( ((SomeDelegate<String>)((x, y) => { MessageBox.Show(x.GetType().ToString()); return (x + y); })).Invoke("2", "3").ToString() );Anonymous
January 31, 2008
The comment has been removedAnonymous
March 29, 2008
The comment has been removedAnonymous
March 31, 2008
An article, concise and to the point. "Keep it simple" is the way to go.Anonymous
April 10, 2008
Other names I use for "=>" are "maps to" or "evaluates to". But ofcourse no answer is "right" ;-)Anonymous
May 08, 2008
In JavaScript lambdas are just regular functions. For example, this expression throws a lambda throw function(x) x * x; which can be caught later and called as a regular function. Not that it is of any use but demonstrates the flexibility.Anonymous
July 23, 2008
I had an interesting conversation with my nephew the other day. He is a very bright CS student workingAnonymous
July 31, 2008
PostedbyscottonTuesday,May08,2007 ThisarticlelooksatJavaScrip...Anonymous
August 30, 2008
Another name for 'statement lambdas' is 'blocks'. Are you planning a follow-up to talk about some more advanced uses, like closures? Closures, in my experience, tend to surprise people and they don't usually get it at first, so that might be something else cool to cover. As far as naming the => operator, in Ruby circles, it's known by the name of a certain member of the male anatomy starting with the letter 'P' :)Anonymous
October 02, 2008
I generally pronounce "=>" as "goes to", but I also like "maps to" and "evaluates to". @chadmyers: Remind me never to involve myself in any Ruby circles. :PAnonymous
October 09, 2008
@chadmyers, the post on closures is now written: http://blogs.msdn.com/ericwhite/archive/2008/09/12/closures.aspx -EricAnonymous
October 27, 2008
If you are using Linq to SQL, instead of writing regular Linq Queries, you should be using Compiled QueriesAnonymous
October 27, 2008
If you are using Linq to SQL, instead of writing regular Linq Queries, you should be using Compiled QueriesAnonymous
November 07, 2008
=> is actually pronounced as "goes to"Anonymous
December 31, 2008
Hey Eric, Thanks for the great article. I've been searching the net for a good explanation of Lambda Expressions and by far yours is the best. I really like how you walks us through the process from C# 1.0 to C#3.0 showing the progression. By doing that you made the transition very easy to follow. It's wonderful when someone is explaining something and they don't make the assumption that you have previous knowledge. By walking us through the progression I don't think anyone can leave this article not understanding the topic. Well done, I'll have to check out your other articles. Regards, Garfield.Anonymous
January 05, 2009
Thanks, Garfield - I appreciate the compliment. :)Anonymous
January 10, 2009
Note : This entry was originally posted on 11/28/2008 11:58:09 AM. I present at a lot of the local FloridaAnonymous
April 02, 2009
WhatASP.NETDevelopersShouldKnowAboutJavaScript转自:http://odetocode.com/Articles/473.aspxPosted...Anonymous
April 05, 2009
"All lambda expressions use the lambda operator =>, which is read as "goes to" " http://msdn.microsoft.com/en-us/library/bb397687.aspxAnonymous
June 24, 2009
awesome Eric. I hope you keep making concepts easier to understand. Thank you.Anonymous
August 26, 2009
Excellent work! You really made this much easier to grasp and more importantly use in my code... ThanksAnonymous
August 28, 2009
I've recently switched over from Java to C#, subsequently bought two books from Manning but was struggling to understand delegates and lambda expressions. I understood it immediately when I read your article. It's excellent, thanks.Anonymous
August 30, 2009
Very good article and thanks! I just wonder what is: () => Could you please explain this one also? I encountered this a lot in "Composite Application Guidance for WPF and Silverlight" which I keep confused. Example: var myAction = new ActionHelper() { ActionToExecute = () => calledThreadID = Thread.CurrentThread.ManagedThreadId }; and: ServiceLocator.SetLocatorProvider( () => new MockServiceLocator( () => mockRegionContentRegistry)); Thanks AlanAnonymous
August 30, 2009
Hi Alan, What you're seeing is a statement lambda expression that takes no arguments, and returns void. Here is similar code that you can paste into a console application and run: Action a = () => { Console.WriteLine("in a statement lambda expression that takes no arguments and returns void."); }; a(); There are various flavors of the Action delegate type, just like there are various flabors of the Func delegate type. Actions are delegate types that return void. What you're seeing in the "Composite Application Guidance for WPF and Silverlight" is that there is a void delegate that takes no arguments, and they are using Lambda expression syntax as a convenient way to initialize the delegate. They could have written a function, declared and initialized a delegate, and assigned the delegate, but this would be more verbose. (I've updated the post to include examples of this variety of lambda expression.) Does that help? -EricAnonymous
August 30, 2009
Eic: Thank you very much for your timely response. The code makes sense to me now. I've been Googling the () => and couldn't find any thing until your posting showed up. Thanks AlanAnonymous
October 20, 2009
Nice article with clear breakup of lambda expresssion.Anonymous
October 21, 2009
Thank you, it helped to grab the basics of Lambda Expressions.Anonymous
December 06, 2009
Excellent job breaking down how lamda works. This was very helpful. I will definitely be reading more of your postings. Thank youAnonymous
December 10, 2009
Very nice explanation. I especially like combining lambda expressions with Func classAnonymous
December 20, 2009
why so overcomplicated: x => { if (x <= 3) return true; else if (x >= 7) return true; return false; } if one can do this: x => { return (x <= 3 || x >= 7); }Anonymous
December 20, 2009
Hi, ebody, my main point in that example was to demonstrate a statement lambda expression. Of course, that particular example can be simplified even further to x => x <= 3 || x >= 7. Typical use of a statement lambda expression is where you need to implement fairly complex semantics, computing separate return values in different code blocks, so that is why I wrote the example as I did. But I didn't want to pick an example where the code of the example interferred with the point I was making. Does that make sense? -EricAnonymous
December 21, 2009
Good argumentation. I'm on your side now :]Anonymous
December 21, 2009
Can you tell me please @EricWhite or anyone reading the comments what is the performance of this example: int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where(x => x > 5)) Console.WriteLine(i); is this looping twice on that array, first filtering the values and then looping on the result or is there internally only one loop where each element is tested and either returned or skipped? I wonder whether this is not faster: foreach (int i in source) if(i > 5) Console.WriteLine(i);Anonymous
December 21, 2009
Hi, @ebody, that's a great question. The two examples you present basically perform almost identically. The Where extension method is 'lazy'. Internally, there is only one loop where each element is tested, and then either returned or skipped. For a detailed explanation of laziness, see Lazy Evaluation, and in contrast, Eager Evaluation. There is a little bit of overhead when using laziness, in that there is a closure object created by the call to Where. This is an object that keeps the state of where you are in the iteration, as well as references to any variables that you refer to in the lambda expression (they are placed on the heap, even if they are local variables, see Closures for more info). There is a function call to a function that is internal to the closure for every item in the collection, so that is a bit of overhead. Also, using the Where extension method creates a new, short-lived object on the heap for every item that is returned. However, the garbage collector is optimized for this scenario. I have written some recursive LINQ to XML transformations that work on LARGE Open XML documents. These transformations allocate a huge number of short-lived objects, but their performance is amazingly fast, even on a slow computer. (I do almost all of my development and testing on an old, slow laptop - basically a netbook.) There have been a very few cases where I needed to optimize code to perform faster, and I never focused on elmination of closures. Instead, I focused on selective materialization of intermediate results into arrays or collections, and I've always been able to achieve my performance goals. For instance, if I am querying a huge Open XML document, instead of iterating over the entire, huge document every time, I may first 'materialize' the paragraphs I'm interested in, and contents of the paragraphs into a List<T>. Then subsequent iterations are over the much shorter List<T> instead of over the whole document. -EricAnonymous
January 09, 2010
In the Using an Anonymous Method paragraph there is this piece of code: ChangeInt myDelegate = new ChangeInt( delegate(int x) { return x * 2; } ); The only thing I don't understand about this is why you give the delegate yet another delegate. Why isn't it given a method?Anonymous
January 09, 2010
Thanks for the very clear explanation! What I am additionally looking for is the c# specification that explains why the following code, taken from your example above, works: static List<T> MyWhereMethod<T>(IEnumerable<T> source, Func<T, bool> predicate) {...} ... int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; List<int> filteredList = MyWhereMethod(source, i => i >= 5); How does the resolving work for the function-call with signature List<int> MyWhereMethod(IEnumerable<int>, Func<T, bool>)? There isn't such a signature in this namespace, at least not literally. Contrary to my expectations the compiler apparently is smarter than I thought and resolves to the given MyWhereMethod<T>. Why is that?Anonymous
January 09, 2010
The comment has been removedAnonymous
January 10, 2010
The comment has been removedAnonymous
January 10, 2010
Hi Benjamin, Sorry, I didn't take the proper time to write the last answer. Here is how this works: // the following is the definition of a delegate type public delegate int ChangeInt(int x); // the following is a declaration of a delegate ChangeInt myDelegate = new ChangeInt( delegate(int x) { return x * 2; } ); In a declaration, when newing up the instance of a delegate, you can pass the name of a method that has the correct signature, which is how the example immediately preceding the one that we're discussing works. Or when newing up the instance of a delegate, you can write an anonymous method right there, in place. This uses the delegate keyword, where you declare the types of the arguments and the body of the method immediately following 'delegate'. Does that make sense? -EricAnonymous
January 10, 2010
I think I do. In the second example there is not yet a definition of a delegate, but you make one with ChangeInt myDelegate = new ChangeInt(delegate(int x) {return x * 2;}); If that's correct, than I understand. Thank you very much for taking the time Eric!Anonymous
January 11, 2010
While fiddling with code, I noticed you can also write this: public delegate int ChangeInt(int x); ChangeInt myDelegate = delegate(int x) { return x * 2; };} It produces the same output, no errors. Is there any difference between the two?Anonymous
January 24, 2010
Hi Benjamin, No, there is no difference between the two. The compiler can initialize the delegate with the anonymous method that you create with the delegate keyword. This is similar to code that you could write like this: ChangeInt myDelegate = (int x) => { return x * 2; }; or ChangeInt myDelegate => x => x * 2; For what its worth, I never use the delegate keyword, as you can always use the lambda expression syntax. After you become accustomed to lambda expression syntax, it becomes more natural, in my opinion. -EricAnonymous
February 05, 2010
Excellent article! You made it so easy to understand. Thank you so much!Anonymous
February 07, 2010
Thanks Eric for the Nice Article.Anonymous
February 16, 2010
Thanks for the article, it helped clear a few things up for me! I have a question though and I may be completely missing something here, but take the following code from the article: int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source.Where(x => x > 5)) Console.WriteLine(i); Is there an advantage to using Lambda to extract data from the array rather than LINQ?Anonymous
February 16, 2010
Hi Andrew, Query expressions are directly translated to equivalent expressions using lambda expressions. The nomenclature is that when you express them using lambda expressions, they are written in 'method syntax'. For example, another way to write the query that you referred to is like this: int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; var q = source.Where(x => x > 5); foreach (int i in q) Console.WriteLine(i); This is exactly the same as if you write this: int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; var q = from x in source where x > 5 select x; foreach (int i in q) Console.WriteLine(i); The second form is translated to the first by the compiler. I've written a few things that discuss this: http://blogs.msdn.com/ericwhite/pages/Quick-Intro-to-Query-Expressions.aspx http://blogs.msdn.com/ericwhite/pages/an-example-presented-in-both-coding-styles.aspx http://blogs.msdn.com/ericwhite/pages/statically-compiled-queries.aspx For what it's worth, I have gravitated completely to using 'method syntax'. There are queries that you can write in method syntax that you can't write using query expressions, but the reverse is not true, so I personally find it more convenient to consistently use method syntax. -EricAnonymous
March 25, 2010
Thanks a lot EricWhite for your efforts. Your tutorial is so simple yet so authoritative. Its a breeze to learn lambadas/FP through your tutorial(s). Would you care to write some day on Expression trees using lambadas as mentioned. In the mean time can you suggest some resources which are as good as yours for learning Expression trees through FP. -PanksAnonymous
March 25, 2010
Hi Panks, I'm glad it's useful. The SharePoint 2010 managed client side object model (CSOM) includes an interesting use of lambda expressions that are processed by expression trees. I'm planning on writing a blog post/MSDN article that explains that use of lambda expressions. It would be fun to also write a more general explanation of expression trees. -EricAnonymous
March 31, 2010
I loved reading this. Now I know lambda. Thanks everyoneAnonymous
March 31, 2010
Really good article to understand Lamda ExpressionAnonymous
May 10, 2010
@Eric: Brilliant Article Although I have a question: AS if can you please let me know ,wat are the scenarios where we should use each of the following : anonymous delegates vs. functional calls vs. lambda expression to optimize the performance of the application.Anonymous
May 24, 2010
What is the advantage of LAMBDA Expression over standard SQLAnonymous
May 04, 2011
I see what it does but I really don't know why we are all still coding? 30 years on and the code gets more complex to do the same old things. One day someone will design th "codeless development system" Interesting article though, I will need to put some in a project now as it won't be fashionable if you don't put the latest techy stuff in(just kidding) P CheersAnonymous
November 14, 2011
Hi, I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of lambda expression in c# and it will help me a lot. This link... www.mindstick.com/.../Lambda%20Expression%20in%20c I have found another nice post over internet. It is also helpful to complete my task. Thank you very much!Anonymous
March 26, 2012
Hi Really you had written a very good article. Your way is very simple to explore your knowledge about lambda expression. I had also written a small blog on lambda expression that how to use lambda expression with use defined datatypes. I used lambda expression for finding records. dabbu-csharphelp.blogspot.in/.../lambda-expression.html I hope this blog is also useful to those users who wants to know about lambda expressio that how to find records from list using lambda expression. thanks to sharing this useful article.Anonymous
October 07, 2013
The comment has been removedAnonymous
October 07, 2013
The code containing the "lambda expression": int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; var q = source.Where(x => x > 5); foreach (int i in q) Console.WriteLine(i); Is the same as: int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 }; foreach (int i in source) if (i > 5) Console.WriteLine(i); Which is simpler? Which executes more quickly? Exactly. Sometimes, simpler is better. Especially when it comes to maintaining a huge code base. "Cool" does not equal "better" in the real world.Anonymous
November 28, 2014
Good to see that such type of articles are there for us(The beginers) :)