F# List.map equivalent in C#?

后端 未结 2 1066
借酒劲吻你
借酒劲吻你 2021-02-06 19:58

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:<

相关标签:
2条回答
  • 2021-02-06 20:36

    That is LINQ's Select - i.e.

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

    or

    var newSequence = from x in originalSequence
                      select {translation};
    
    0 讨论(0)
  • 2021-02-06 20:40

    ConvertAll is the built-in function:

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

    Available since .NET version 2.0.

    MSDN code example:

    using System;
    using System.Drawing;
    using System.Collections.Generic;
    
    public class Example
    {
        public static void Main()
        {
            List<PointF> lpf = new List<PointF>();
    
            lpf.Add(new PointF(27.8F, 32.62F));
            lpf.Add(new PointF(99.3F, 147.273F));
            lpf.Add(new PointF(7.5F, 1412.2F));
    
            Console.WriteLine();
            foreach( PointF p in lpf )
            {
                Console.WriteLine(p);
            }
    
            List<Point> lp = lpf.ConvertAll( 
                new Converter<PointF, Point>(PointFToPoint));
    
            Console.WriteLine();
            foreach( Point p in lp )
            {
                Console.WriteLine(p);
            }
        }
    
        public static Point PointFToPoint(PointF pf)
        {
            return new Point(((int) pf.X), ((int) pf.Y));
        }
    }
    
    /* This code example produces the following output:
    
    {X=27.8, Y=32.62}
    {X=99.3, Y=147.273}
    {X=7.5, Y=1412.2}
    
    {X=27,Y=32}
    {X=99,Y=147}
    {X=7,Y=1412}
     */
    
    0 讨论(0)
提交回复
热议问题