Python for the .NET Developer Transcripts
Chapter: The Python Language
Lecture: C# lambda expressions

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Lambda expressions were introduced with LINQ back in C# 3.0, in my opinion, they are one of the most
0:07 important additions to the language along with LINQ itself. That was groundbreaking work they did from C# 2.0
0:14 to C# 3.0, so, let's look at that really quick here and see if Python has some kind of equivalent. We're going to take a random list of numbers here
0:23 list of integers. And I would like to sort them, normally you could just do real simple stuff like data.sort, you'd be done.
0:32 However, I don't want to sort them smallest to largest I want to sort them some other way or maybe I have a list
0:37 of customers I want to sort them by their total value descending right so I need some function to pass to sort
0:43 to say, well, don't just sort by comparing the items directly but apply this change or this algorithm to each comparison
0:51 so what we can do is we pass a lambda expression here. We say there are parameters n and m. They go to the expression the return value.
1:02 Math.Abs(n) - Math.Abs(m) so what we're trying to do is sort by the size of these elements, forgetting, whether they're
1:10 negative or positive, if you could just take away all the negative values and just do regular sort
1:14 and then put them back and that's what we're trying to do. So we're going to print it out here. That's a little function print collection again.
1:21 And I'd also like to, you know, maybe do some other stuff like given those elements, I would like to convert that to an collection that is double that
1:29 double each element in the list, after it's been sorted. We can use little LINQ to objects here, and pass
1:35 a lambda expression to LINQ and say to the Select function and say, given any element in the list I want you to say the next element is two times that.
1:44 So let's just run this real quick to see what we get. The first one is the perfect sorting 11 23 that all seems normal till you say 21, -34 55.
1:56 Notice it's sorting by amplitude or magnitude of those numbers. And then the second one that I pass off to the print
2:03 using that select statement actually created a new collection that is double the first collection. Interestingly, just like the stuff we talked about
2:12 with generators and Fibonacci sequence, this is also one of those lazy collections which is additionally, awesome.
2:18 These are lambda expressions, they're really great instead of writing a whole different function of processes
2:23 I can literally write this incredibly small bit of code here and just pass it to the select statement and modify
2:31 the behavior select or sort or things like that really a nice feature of the language.


Talk Python's Mastodon Michael Kennedy's Mastodon