アットウィキロゴ

ショートコードプログラミング

TryParseを使用する

string src = "123";
int result;
Console.WriteLine(int.TryParse(src,out result) ? result : -1);
処理の重い例外を避けることができる。定石は if(int.Tryparse(xxx, out yyy)){処理}

null合体演算子

string a = "We are the Hello World!!";
Console.WriteLine(a ?? "(null)");
nullポインタ参照を劇的に減らす事ができる。
WindowsフォームアプリケーションのNullチェックにも適用可能。
string str = (string)listBox1.SelectedItem ?? "not selected";

引数にラムダ式

大事

名前を指定したメソッド呼出

dynamicが一番

列挙可能なオブジェクトを作ってみる

class Sample : IEnumerable<int>{
  public IEnumerator<int> GetEnumerator(){
    for(int i=0,i<10; i++) yield return i;
 }

IEnumerator IEnumerator.GetEnumerator(){
  return GetEnumerator();
}
yield returnが本当に便利。foreachが使える。

連番の生成

Enumerable.Range(1,10)

配列まとめ

var found = a.FindAll((c)=>c>0); // 0よりも大きい数値を返す ~ foreach(var n in a.Where((c)=> c > 0) //ループなしで塊をさばく1
a.Where((c)=>c>0).Count() //ループなしで塊をさばく2 ~ foreach(var n in a.SkipWhile(c,i)=>i <= 0)) // 先頭行を飛ばす。CSVとかで便利

Mainメソッド以外からコマンドラインを参照したい

Environment.GetCommandLineArgs()で解決

IsNullOrWhiteSpace,IsNullOrEmptyの活用

便利

文字列の分割

string[] ar = s.Split(new[] {',',' '});
Array.ForEach(ar,(c)=> Console.WriteLine("[" + c + "]"));

テキストファイル全体の読み込み

File.ReadAllText(args[0]); File.WriteAllText(args[0],testdata)もある
File.ReadLines(args[0]).Where(c => c.Containss("xxx")).Count()など

タスクの並列実行

System.Threading.Tasks > System.Threading Parallel.Invokeもある

配列の計算を2つのコアに分散させる

Parallel.Forを使うべき。システムがコア数から分散数を決めてくれるため、常に最適な分割数となる。
string[] a = {"1","2",..};
int[] b = new int[a.length];
Parallel.For(0,a.Length,(n) => { b[n] = int.Parse(a[n]) });

Parallel.ForEachも便利。

Windowsフォームアプリケーションの処理

task = new Task(){ () => ^ { this.Invoke*1 }
タスクをDictionaryに登録して実行するのも割とありな気がする。

最終更新:2015年08月18日 21:47

*1 Action)(()=>{ x.Text = "test"}