How do you use C # lambda expressions?

Fill in your messages. I'll start with a couple, see how much we can collect.

To provide built-in event handlers, for example

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

Search for items in a collection

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

To iterate through a collection, for example

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

Let them come !!

+6
c # lambda
source share
7 answers

Return custom object:

 var dude = mySource.Select(x => new {Name = x.name, Surname = x.surname}); 
+3
source share

One line function

 Func<int, int> multiply = x => x * 2; int y = multiply(4); 
+2
source share

Here is a little different - you can use them (for example, this) to mimic the missing "infoof" / "nameof" operators in C # - that is, instead of hard coding the property name as a string, you can use lambda. This means that it is checked at compile time (which lines cannot be).

Obviously, for this there is a cost of execution, therefore, "just for fun", but interesting ...

+2
source share

With a method call to update the user interface from a multi-threaded Componentet event

 void Task_Progress(object sender,TaskProgressArgs e) { BeginInvoke(new MethodInvoker(() => UpdateProgress(e))); } 
+1
source share

Creating a battery.

  static Func<int, int> Foo(int n) { return a => n += a; } 

Note the use of closure here. it creates a drive that "remembers" the value of n between calls - without a class or instance variable.

0
source share

For aggregate operations with Linq:

 public Double GetLengthOfElements(string[] wordArr) { double count = wordArr.Sum(word => word.Length); return count; } 

Sure kicks using foreach

0
source share

To express an unnamed function.

-one
source share

All Articles