Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,393 questions

52,502 answers

573 users

How to apply a callback to an array (apply a function to each element) in C#

4 Answers

0 votes
// Using Array.ForEach with a callback

using System;

public class CallbackProgram
{
    public static void Main(string[] args)
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        // The callback is the lambda: n => Console.WriteLine(n * 2)
        Array.ForEach(numbers, n => Console.WriteLine(n * 2));
    }
}



/*
run:

2
4
6
8
10

*/

 



answered 6 days ago by avibootz
0 votes
// Using a custom callback method

using System;

public class CallbackProgram
{
    // callback
    public static void PrintSquare(int x) {
        Console.WriteLine(x * x);
    }

    public static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5 };

        Array.ForEach(arr, PrintSquare);
    }
}


/*
run:

1
4
9
16
25

*/

 



answered 6 days ago by avibootz
0 votes
// Use LINQ Select when the callback returns a value

using System;
using System.Linq;

public class CallbackProgram
{
    public static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5 };
        
        // Callback: n => n * 2
        var doubled_array = arr.Select(n => n * 2).ToArray();

        // Print the array after callback
        Console.WriteLine("Doubled array:");
        Array.ForEach(doubled_array, n => Console.Write(n + " "));
        Console.WriteLine();
    }
}



/*
run:

Doubled array:
2 4 6 8 10 

*/

 



answered 6 days ago by avibootz
edited 6 days ago by avibootz
0 votes
// Use Func<T, TResult> if the callback must return something

using System;
using System.Linq;

public class CallbackProgram
{
    public static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5 };
        
        Func<int, int> callback = x => x + 10;

        var result = arr.Select(callback).ToArray();


        // Print the array after callback
        Console.WriteLine("Result:");
        Array.ForEach(result, n => Console.Write(n + " "));
        Console.WriteLine();
    }
}



/*
run:

Result:
11 12 13 14 15 

*/

 



answered 6 days ago by avibootz
...