Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what ways do you make use of C# Lambda Expressions? [closed]

Pour in your posts. I'll start with a couple, let us see how much we can collect.

To provide inline event handlers like

button.Click += (sender,args) =>
{
};

To find items in a collection

 var dogs= animals.Where(animal => animal.Type == "dog");

For iterating a collection, like

 animals.ForEach(animal=>Console.WriteLine(animal.Name));

Let them come!!

like image 378
amazedsaint Avatar asked Dec 13 '08 13:12

amazedsaint


3 Answers

Returning an custom object:

var dude = mySource.Select(x => new {Name = x.name, Surname = x.surname});
like image 78
Andreas Grech Avatar answered Sep 19 '22 17:09

Andreas Grech


One line function

Func<int, int> multiply = x => x * 2;
int y = multiply(4);
like image 23
Binoj Antony Avatar answered Sep 20 '22 17:09

Binoj Antony


Here's a slightly different one - you can use them (like this) to simulate the missing "infoof"/"nameof" operators in C# - i.e. so that instead of hard-coding to a property name as a string, you can use a lambda. This means that it is validated at compile time (which strings can't be).

There is obviously a performance cost to this, hence "just for fun", but interesting...

like image 43
Marc Gravell Avatar answered Sep 20 '22 17:09

Marc Gravell