Listによる配列操作
プログラミングC# 第6版 7.2
List
通常の配列では配列の要素数が固定されてしまうという問題がありましたが、List
というわけで動作確認してみます。
using System; using System.Collections.Generic; // List<T>を使うのに必要 class Program { static void Main () { List<string> strs = new List<string>(); strs.Add("foo"); strs.Add("bar"); strs.ForEach( e => Console.WriteLine(e) ); } }
$ main foo bar
良いですね。
他にも色々な機能があるので適当に動作確認してみます。
using System; using System.Collections.Generic; class Program { static void Main () { List<string> strs = new List<string>(); strs.Add("foo"); strs.Add("bar"); // 配列の要素数 Console.WriteLine("要素数: "+strs.Count); // []で要素に参照 Console.WriteLine("要素[0]の値: "+strs[0]); // []で書き換えることも可能 strs[1] = "BAR"; Console.WriteLine("要素[1]の値: "+strs[1]); // 配列の反転 strs.Reverse(); // 通常の配列型に変換 string[] str_array = strs.ToArray(); foreach(string s in str_array) { Console.WriteLine(s); } } }
$ main 要素数: 2 要素[0]の値: foo 要素[1]の値: BAR BAR foo
便利ですね。配列操作としては他にもStack