string src = "123";
int result;
Console.WriteLine(int.TryParse(src,out result) ? result : -1);
処理の重い例外を避けることができる。定石は if(int.Tryparse(xxx, out yyy)){処理}
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とかで便利
Environment.GetCommandLineArgs()で解決
便利
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もある
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も便利。
task = new Task(){ () => ^
{ this.Invoke(*1) }
タスクをDictionaryに登録して実行するのも割とありな気がする。
*1 Action)(()=>{ x.Text = "test"}