Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when should i use lambda expressions which comes with C# 3.0?

Tags:

c#

lambda

c#-3.0

Hai guys,

My fellow developers were talking about lambda expressions this morning. So i decided to ask it here in SO

  • when should i use lambda expression which comes with C# 3.0?
like image 893
ACP Avatar asked Jan 12 '10 06:01

ACP


2 Answers

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

expect of using

del myDelegate = delegate(int x){return x*x; };
int j = myDelegate(5); //j = 25

you can write

del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
like image 148
Arsen Mkrtchyan Avatar answered Oct 29 '22 12:10

Arsen Mkrtchyan


I don't think that there is a general rule when your should use them, but if I look to myself I tend to use them whenever I use anonymous methods. Most often this happens when spawning some code in a new thread using the ThreadPool, or when doing LINQ queries.

ThreadPool example:

ThreadPool.QueueUserWorkItem(state => {
    // the code to run on separate thread goes here
});

LINQ:

var myItems = GetSomeIEnumerable()
                  .Where(o => o.SomeProperty.Equals("some value"));
                  .OrderBy(o => o.SomeOtherProperty);
like image 37
Fredrik Mörk Avatar answered Oct 29 '22 13:10

Fredrik Mörk