Writing extension methods with Action / Func / Delegates / Lambda in VB and C #

Firstly, I can’t make out the functional / lambda aspects of .NET 3.5. I use these functions every day in LINQ, but my problem is understanding the implementation and what they really mean (Lambda? System.Func? Etc, etc.)

With this in mind, the following will be achieved:

As an example, I would like to have an extension method for List (Of T) that sets the properties of all objects in List for a specific value and returns an updated List (Of T). It will be called like this:

VB:

 Dim someList As List(Of TextBox) =  (New List(Of TextBox)).UpdateExtension(Function(txtb) txtb.Text = "something")

FROM#:

List<TextBox> someList = (new List<TextBox>()).UpdateExtension(txtb => txtb.Text = "something");

What does the extension method look like in VB and C #?

i.e:

 <Extension()> _
 Public Function UpdateExtension(Of T)(ByVal source As List(Of T), ByVal predicate As ??) As List(Of T)
        '??
 End Function

Hurrah!

EDIT

, .ForEach(). , , - .ForEach(), .

+3
3

. Select ForEach. , , . .

VB.Net

<Extension()> _
Public Function UpdateExtension(Of T)(ByVal source As IEnumerable(Of T), ByVal del As Action(Of T)) As IEnumerable(Of T)
  For Each cur in source
    del(cur)
  Next
  Return source
End Function

#

public static IEnumerable<T> UpdateExtension<T>(this IEnumerable<T> source, Action<T> del) {
  foreach ( var cur in source ) {
    del(cur);
  }
  return source;
}
+2

, , , .ForEach().

, , IEnumerable, . , :

MyEnumerable.Count() > 2
MyEnumerable.Skip(2).Any()

, IEnumerable, # yield. , , .

, . Func , . Action Func, void, Predicate - , bool.

+2

, , . , :

public static class ListBoxExtensions
{
  public static List<TextBox> SetToValue(this List<TextBox> txtBoxes, string sValue)
  {
    txtBoxes.ForEach(txtBox => txtBox.Text = sValue);
    return txtBoxes;
  }
}

Windows :

private void Form1_Load(object sender, EventArgs e)
{
  List<TextBox> boxes = new List<TextBox>
                        {
                          textBox1,
                          textBox2,
                          textBox3
                        }.SetToValue("Hello");
}

- VB.

, .

+1

Source: https://habr.com/ru/post/1707648/


All Articles