簡體   English   中英

C# 中的 F# List.map 等價物?

[英]F# List.map equivalent in C#?

C# 中是否有與 F# 的 List.map 函數等效的功能? 即對列表中的每個元素應用一個函數並返回一個包含結果的新列表。

就像是:

    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);
    }

是否已經有內置方式或者我應該只編寫自定義擴展?

那就是 LINQ 的Select - 即

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

或者

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

ConvertAll是內置函數:

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

從 .NET 2.0 版開始可用。

MSDN 代碼示例:

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}
 */

為了簡化@codeape 所說的:

List<string> result = ListWithAnyObjects.ConvertAll<string>(obj => obj.ToString());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM