tags:

views:

552

answers:

2

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?

+16  A: 

That is LINQ's Select - i.e.

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

or

var newSequence = from x in originalSequence
                  select {translation};
Marc Gravell
+1 Much too fast :)
Andrew Hare
duh, thanks a lot Marc!
Andy J
+6  A: 

ConvertAll is the built-in function:

public List<TOutput> ConvertAll<TOutput>(
    Converter<T, TOutput> converter
)

Documentation: http://msdn.microsoft.com/en-us/library/73fe8cwf.aspx

Available since .NET version 2.0.

codeape