2009-10-20 34 views
43

Có tương đương với hàm List.map của F # trong C# không? tức là áp dụng một hàm cho từng phần tử trong danh sách và trả về một danh sách mới chứa kết quả.F # List.map tương đương trong C#?

Cái gì như:

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

Có đã tích hợp sẵn trong cách này hay nên tôi chỉ viết phần mở rộng tùy chỉnh?

Trả lời

76

Đó là LINQ của Select - ví dụ:

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

hoặc

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

ConvertAll là built-in chức năng:

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

sẵn từ NET phiên bản 2.0.

Ví dụ về mã 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} 
*/ 
Các vấn đề liên quan