F# List.map 在 C# 中等效吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1594000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
F# List.map equivalent in C#?
提问by Andrew Jones
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.
在 C# 中是否有等效于 F# 的 List.map 函数?即对列表中的每个元素应用一个函数并返回一个包含结果的新列表。
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?
是否已经有内置的方法,还是我应该编写自定义扩展?
采纳答案by Marc Gravell
That is LINQ's Select
- i.e.
那是 LINQ 的Select
- 即
var newSequence = originalSequence.Select(x => {translation});
or
或者
var newSequence = from x in originalSequence
select {translation};
回答by codeape
ConvertAll
is the built-in function:
ConvertAll
是内置函数:
public List<TOutput> ConvertAll<TOutput>(
Converter<T, TOutput> converter
)
Available since .NET version 2.0.
自 .NET 2.0 版起可用。
MSDN code example:
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}
*/