views:

200

answers:

7
var seq = Enumerable.Range(1, 10).Reverse();
var sort1 = seq.OrderBy(i => i);
var sort2 = seq.OrderBy(delegate(int i) { return i; });

i think sort2 is more explicit but sort 1 is shorter. besides that, i don't really know the difference. what is the recommended way of doing this?

+2  A: 

I much prefer the lambda syntax (sort1) where possible. I only use the more verbose syntaxes where they are required. I consider the extra stuff non-productive code that just gets in the way of understanding what I'm writing.

Edit: Unless of course I'm working on a .NET 2.0 app, where you can't use the lambda syntax. Then, I'm just glad I at least have anonymous methods.

Jonathan
You can use lambdas for .NET 2.0 projects so long as you're using VS2008 and targeting .NET 2.0. It's worth distinguishing between language version and framework version.
Jon Skeet
+9  A: 

Lambda expressions are (IMO) better than anonymous methods in every case except where you don't care about the parameters, in which case there's a nice shortcut:

// Lambda expression has to specify parameter types
EventHandler x = (sender, args) => Console.WriteLine("Hi");

// Anonymous method can ignore them
EventHandler x = delegate { Console.WriteLine("Hi"); };

Lambda expressions have two other "problems" IMO:

  • Obviously they're not available if you're not using C# 3. (Although you can target .NET 2.0 from VS2008 and still use them.)
  • The syntax for a parameterless lambda expresssion is somewhat clunky:

    () => stuff
    
Jon Skeet
is it a MUST that lambda has to specify parameter types?EventHandler x = () => Console.WriteLine("Hi");
Rony
That's explicitly specifying an empty list of parameters - which means it isn't convertible to EventHandler.
Jon Skeet
Isn't ()=>stuff going to be _ => stuff in C#4?
Jeff Yates
got it, thanks for your explanation
Rony
@Jeff: Not that I've seen. Don't forget that _ is a valid identifier. I've heard nothing about this, and it doesn't work in beta 1.
Jon Skeet
@Jon: I wasn't sure. I had seen it in a blog somewhere from inside Microsoft. I'll hunt it down - I forgot to follow up on it and find out what it was. Now seems as good a time as any.
Jeff Yates
It's worth mentioning that aside from their concise syntax, Lambdas have one significant advantage over delegates, in that they can be processed by the compiler into either a delegate or an expression tree as needed. A feature that makes it possible to programmatically manipulate the expressions passed in as lambdas.
LBushkin
@LBushkin: Yes indeed :)
Jon Skeet
And another Jon Skeet's Answer. +1
Timotei Dolean
A: 

As far as I know both approaches will generate the exact same IL code (at least in this example), so it's really a matter of taste. I often think lambda tastes nicer.

Fredrik Mörk
+1  A: 

I find this depends on the scenario as the important aspect is making sure the intent of your code is well documented for future maintainers. Therefore, sometimes a lambda works best, but other times an anonymous method is a better option. The problem with lambdas where more than argument is needed, is that the syntax starts to look cluttered, so it can sometimes be useful to use the anonymous method delegate syntax to provide a more recognisable structure.

In the example you have given, the lambda is the better option as it is clear and concise; however, when declaring say an inline event handler, an anonymous method might provide a better solution (with regards to maintainability).

Jeff Yates
When you say "other times a delegate is a better option" I think you mean "other times an anonymous method is a better option". In this case, both expressions are being converted to delegates.
Jon Skeet
@Jon: yes - I was tripping over my words. :)
Jeff Yates
Don't worry about it too much - I'm just a massive terminology pedant :) (That doesn't mean I always get it right, of course!)
Jon Skeet
@Jon: I get called a pedant more than you could imagine - being British surrounded by these Americans, language becomes an issue.
Jeff Yates
A: 

sort1 - Lambdas I think is the prefered way to write Anonymous methods

Rony
Just to be a massive pedant (and hey, I'm commenting on all the other answers :) an anonymous method is by definition the syntax seen in sort2. Both lambda expressions and anonymous methods count as anonymous functions; both can be converted to delegate types; only lambda expressions can be converted to expression trees.
Jon Skeet
+1  A: 

There are few (and I can only think of one off the top) where I like the delegate syntax over the lambda expression ...

public event Action Evt = delegate {};
public event Action Evt = () => { };

... for example. The rest of the time, delegate just gets in the way. Per Jon's comment ...

public event EventHandler Evt = delegate {};
public event EventHandler Evt = (s,ea) => { };
JP Alioto
Actually that's a bad example of the event bit, because Action doesn't take any parameters - the lambda expression is fine here. Change it to EventHandler and the lambda expression becomes ugly because you have to give names to the parameters even if you're not using them.
Jon Skeet
A: 

I prefer lambda-expressions since they offer the the most concise syntax and resemble the lambdas in functional programming languages where this construct originally comes from. When the expression contains more than one statement or unfunctional constructs, I'll use delegate. Parameterless, multi-lined or explicitly typed lambda expressions may look somewhat weird and hence lose their major advantage (being more readable).

g = (x => 2 * f(x) + 1); // Nice functional one-liner

// but

action = delegate (int arg) {
    SendSystemMessage(arg);
    Console.WriteLine("Got value: {0}", arg);
};
Dario