|
Last-modified: 2008-04-14 (月) 23:51:08 (5826d)
Visual Studio 2008と共にリリースされた.NET Framework 3.5の目玉機能の1つが LINQ らしいのだが、私は否定的だ。その理由は、LINQの実現のために追加された機能の乱用が、ソースコードの可読性、保守性を下げ、品質の維持が難しくなると考えるからだ。 LINQ †var query = from cust in customers where cust.City == "Tokyo" orderby cust.Name ascending select new { Name = cust.Name, Phone = cust.Phone }; 上記のクエリ式は、interface IEnumerable<T>に対する拡張メソッドを用いた以下のコードと同じ意味になるらしい。 var query = customers .Where(cust => cust.City == "Tokyo") .OrderBy(cust => cust.Name) .Select(cust => new { Name = cust.Name, Phone = cust.Phone }); こうして見ると、LINQのクエリ式には、.NET Framework 3.5で追加された型推論、オブジェクト初期化子、匿名型、拡張メソッド、ラムダ式が使われていることがわかる。 型推論 †var s = "Hello World!";
オブジェクト初期化子 †Customer cust = new Customer() { Name = "Taro" };
匿名型 †var product = new { Name = "ノート", Price = 100 };
拡張メソッド †namespace ExtensionMethods { public static class MyExtensions { public static int WordCount(this String str) { return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; } } }
ラムダ式 †// define in class delegate bool MyFunc(string str); MyFunc func = str => str == "Tokyo" Console.WriteLine(func("Osaka"))
|