Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ vs Lambda vs Anonymous Methods vs Delegates

  1. Can anyone explain what are the LINQ, Lambda, Anonymous Methods, Delegates meant?

  2. How these 3 are different for each other?

  3. Was one replaceable for another?

I didn't get any concrete answer when i did Googling

like image 456
Gopi Avatar asked Apr 16 '10 10:04

Gopi


People also ask

What is the difference between lambda expression and anonymous methods?

Anonymous class is an inner class without a name, which means that we can declare and instantiate class at the same time. A lambda expression is a short form for writing an anonymous class. By using a lambda expression, we can declare methods without any name.

Is lambda a delegate?

They are actually two very different things. "Delegate" is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name. Lambdas are very much like other methods, except for a couple subtle differences.

What is anonymous method in LINQ?

An anonymous method is a method which doesn't contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods.

Is LINQ faster than lambda?

There is no performance difference between LINQ queries and Lambda expressions.


1 Answers

LINQ is a broad technology name covering a large chunk of .NET 3.5 and the C# 3.0 changes; "query in the language" and tons more.

A delegate is comparable to a function-pointer; a "method handle" as an object, if you like, i.e.

Func<int,int,int> add = (a,b) => a+b;

is a way of writing a delegate that I can then call. Delegates also underpin eventing and other callback approaches.

Anonymous methods are the 2.0 short-hand for creating delegate instances, for example:

someObj.SomeEvent += delegate {
    DoSomething();
};

they also introduced full closures into the language via "captured variables" (not shown above). C# 3.0 introduces lambdas, which can produce the same as anonymous methods:

someObj.SomeEvent += (s,a) => DoSomething();

but which can also be compiled into expression trees for full LINQ against (for example) a database. You can't run a delegate against SQL Server, for example! but:

IQueryable<MyData> source = ...
var filtered = source.Where(row => row.Name == "fred");

can be translated into SQL, as it is compiled into an expression tree (System.Linq.Expression).

So:

  • an anonymous method can be used to create a delegate
  • a lambda might be the same as an anon-method, but not necessarily
like image 59
Marc Gravell Avatar answered Nov 13 '22 11:11

Marc Gravell