Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

What are lambda expressions?


  • Please log in to reply
4 replies to this topic

#1 ArekBulski

ArekBulski

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 480 posts

Posted 09 April 2009 - 01:54 PM

What are lambda expressions?
This is a question I got from Siten some time ago. I wont hide that I hate this one topic. Here are some code shortages you can get by using lambdas. ;)

Lambdas are used instead of delegates, as shortened replacement for them. Many possible usages of lamdas lie in methods of collections, when you want to select some elements, or check is some element or all elements comply with your demands. For a start we need a list:


List<string> originalList = new List<string>()
{
"123a", "", "aabb", "zzxxa", "ccccdd", "so on a", "etc", "...a",
};


Then we can use lambda expressions with methods that require delegates. For example Find, FindAll, Exists, TrueForAll as well as Any, All and some others. The examples below do the same, the only difference is that lambdas-code is shorter and more readable. ;)


List<string> selectiveInclusion =
originalList.FindAll(new Predicate<string>(delegate(string everyobj)
{
return everyobj.Contains("a");
}));

List<string> selectiveInclusion2 =
originalList.FindAll( (string everyobj) =>
{
return everyobj.Contains("a");
});


Here is another example of lambdas. The difference is the same, in the line of method call.


bool isThere123 =
originalList.Exists(new Predicate<string>(delegate(string s)
{
return s == "123a";
}));

bool isThere123lambda =
originalList.Exists( (string s) =>
{
return s == "123a";
});


The full source code is attached. Feel free to play with it.
Regards, :cool:
Arek Bulski.

Attached Files


  • 1

#2 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 09 April 2009 - 04:12 PM

I still haven't figured out what lambda expressions have to do with lambda calculus?
  • 0

#3 ArekBulski

ArekBulski

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 480 posts

Posted 09 April 2009 - 04:47 PM

I still haven't figured out what lambda expressions have to do with lambda calculus?


There is some explanation on Wikipedia. I dont understand English well enough to understand it though. Lambda calculus - Wikipedia, the free encyclopedia
  • 0

#4 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 19 June 2009 - 12:39 PM

Just read this one. Never even saw it before now. Nice tutorial, +rep.
  • 0

#5 ArekBulski

ArekBulski

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 480 posts

Posted 14 August 2009 - 04:46 PM

Thank you, Jordan. Do you think many people just do not use Lambda expressions at all? :)
  • 0




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download