开发者

Seek overview of the '=>' operator

I'm browsing sample asp.net code in an MVC project and开发者_C百科 need a better understanding of the => operator. Plugging => into search engines is non-helpful.

thx


The => syntax creates lambda expressions, which are small functions.

For example, the line

Func<int, int> myFunc = i => 2 * i;

declares a variable of type Func<int, int> (a delegate that takes one integer and returns another one), and assigns it to a lambda expressions that takes a parameter called i (the compiler automatically figures out that i is an int) and returns 2 * i.


Yo can search it as lambda. See here http://msdn.microsoft.com/en-us/library/bb397687.aspx


The => operator, as has been mentioned, represents a lambda expression. This is short-hand for an anonymous delegate. Here is practical example:

If you want to filter all Person objects in a collection to return only Male people, the Where() extension method requires a Func delegate you could create a named delegate like this:

    Func<Person, bool> isMale = delegate(Person peep) { return peep.Gender == "male"; };
    var men = from p in peeps.Where(isMale)
              select p;

Or you could use an anonymous delegate like this:

    var women = from p in peeps.Where(delegate(Person peep) { return peep.Gender != "male"; })
                select p;

The lambda allows you to declare the anonymous delegate using a short-hand, like this:

    var women = from p in peeps.Where(x => x.Gender != "male")
                select p;

Notice the correspondence between delegate(Person peep) and x, and between 'return peep.Gender != "male"and 'x.Gender != "male".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜