F# List.map equivalent in C#?

Andrew Jones picture Andrew Jones · Oct 20, 2009 · Viewed 52.1k times · Source

Is there an equivalent to F#'s List.map function in C#? i.e. apply a function to each element in the list and return a new list containing the results.

Something like:

    public static IEnumerable<TResult> Map<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> funky)
    {
        foreach (TSource element in source)
            yield return funky.Invoke(element);
    }

Is there already a built in way or should I just write the custom extension?

Answer

Marc Gravell picture Marc Gravell · Oct 20, 2009

That is LINQ's Select - i.e.

var newSequence = originalSequence.Select(x => {translation});

or

var newSequence = from x in originalSequence
                  select {translation};