ジェネリックとPredicate(2)
そんなわけで,akirameiさんより早速コメントいただきました.
> arrList.ConvertAll
> ならOKです
試しました.
class Program { static void Main(string[] args) { string[] arr = {"", "aaa", "bbb", "", "", "ccc", ""}; List<string> arrList = new List<string>(arr); List<string> decoratedList = arrList.ConvertAll<string>(delegate(string s) { return "/* " + s + " */"; }); decoratedList.ForEach(delegate(string s) { Console.WriteLine(s); }); } } -- 結果 /* */ /* aaa */ /* bbb */ /* */ /* */ /* ccc */ /* */ --
うわっ!!出来てる.というか,なぜConvertAll
当然int型でも同様のことが出来ます.
class Program { static void Main(string[] args) { int[] arr = {0, 3, 4, 0, 0, 7, 0}; List<int> arrList = new List<int>(arr); List<int> decoratedList = arrList.ConvertAll<int>(delegate(int i) { return i + 100; }); decoratedList.ForEach(delegate(int i) { Console.WriteLine(i); }); } } -- 結果 100 103 104 100 100 107 100 --
まぁ,どう考えても
for (int i=0; i<arrList.Count; i++) { arrList[i] += 100; }
のほうがいいんですけどね.
ところで,akirameiさんの日記にあるNemerleの記法は,すごくシンプルですね.
def decoratedList = arrList.ConvertAll (s => "/* " + s + " */");