Search code examples
c#juliaequivalent

C# equivalent of Julia's map!() method


I'm trying to find C#'s equivalent of Julia's map!() method, which is of void return type and takes a function, a destination and a collection on which the function acts.

The best thing that I could find is C#'s Enumerable.Select(), which takes the function as the third argument, and the collection as the first argument. However, it returns a new collection instead of modifying the one in the "destination". That resembles Julia's map() more.


Solution

  • There's nothing as standard like this, but you can easily add your own extension method to IEnumerable to add this functionality. For example:

    public static void JuliaMap<TFrom, TTo>
    (
        this IEnumerable<TFrom> source, 
        IList<TTo> target, 
        Func<TFrom, TTo> selector
    )
    {
        var next = 0;
        foreach(var value in source)
        {
            var convertedValue = selector(value);
            target[next] = convertedValue;
            next++;
        }
    }
    

    How you can say:

    var numbers = new[]{1, 2, 3};
    var target = new string[3];
    
    numbers.JuliaMap(target, i => (i * 2).ToString());
    

    NOTE: I've left out any error handling. For example, you'll want to make sure that the target list is long enough to take the inserted value.