Extension List.Map

C# でこういうことできないんだっけ?

using System;
using System.Collections.Generic;
using System.Linq;

namespace CsConsole3
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> ls = new List<int>() {3, 1, 4};

            ls.ForEach(x => ++x); // 全要素に+1

            ls.ForEach(Console.WriteLine); // 3,1,4...書き換わらないな〜
        }
    }
}


試しに、全要素に対する操作を行うメソッドを作ってみた

using System;
using System.Collections.Generic;
using System.Linq;

namespace Shand.Extension
{
    public static partial class Extension
    {
        public static List<T> Map<T>(this List<T> source, Func<T, T> func)
        {
            List<T> result = new List<T>();

            foreach (T item in source)
            {
                result.Add(func(item));
            }

            return result;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using Shand.Extension;

namespace CsConsole3
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> ls = new List<int>() {3, 1, 4};

            ls = ls.Map(x => ++x); // 全要素に+1したリストを返す

            ls.ForEach(Console.WriteLine); // 4, 2, 6
        }
    }
}

と、ここまで作ったところで ConvertAll の存在を思い出した