C# - コレクション - List<T> その2
List
using System; using System.Collections.Generic; //List(デリゲート型を引数にするメソッド) class MyMain { public static void Main(string[] args) { List<string> ary = new List<string>(){"one","two","three","four","five"}; //'o'を含む要素があるか Console.WriteLine( ary.Exists( x=>x.IndexOf('o')>=0) ); //True //'o'を含む最初の要素 Console.WriteLine( ary.Find( x=>x.IndexOf('o')>=0) ); //one //'o'を含む最後の要素(後ろから確認し最初にヒットした要素) Console.WriteLine( ary.FindLast( x=>x.IndexOf('o')>=0) ); //four //'o'を含む全ての要素 PrintArray( ary.FindAll( x=>x.IndexOf('o')>=0) ); //one two four //文字数順に並び替え ary.Sort( (x,y)=> x.Length - y.Length ); PrintArray( ary ); //two one four five three //要素に'[',']'を追加したものを表示 ary.ForEach( (x)=> Console.Write("[" + x + "] ") ); //[two] [one] [four] [five] [three] Console.WriteLine(); //要素を別のオブジェクトに変換したListを生成 // string型からint型に変換するデリゲート型 Converter<string, int> cv = s => s.Length; //変換の実行 List<int> a2 = ary.ConvertAll( cv ); a2.ForEach( e => Console.Write("{0} ", e) );//3 3 4 4 5 Console.WriteLine(); //'o'を含む要素を削除 ary.RemoveAll( x=>x.IndexOf('o')>=0 ); PrintArray( ary ); //five three } private static void PrintArray(List<string> a){ foreach(var e in a) { Console.Write("{0} ", e); } Console.WriteLine(); } }