[Code Project]貧者のためのLinq
Poor Man's Linq in Visual Studio 2005
http://www.codeproject.com/KB/linq/linq2005.aspx
より。
Introduction
Language INtegrated Query in C# 3.0 is pure joy to use. Once you try it, you don't want to stop.But a few of us, for whatever reason, are still using Visual Studio 2005. In my case, I didn't want to pay $550 for the upgrade to VS2008 Pro, but I didn't want to lose features like Macros and Code Diagrams by switching to Visual C# Express Edition or SharpDevelop. So I came up with a way I could use Linq-to-Objects in C# 2.0.
Note: if you are stuck with .NET Framework 2.0 but you are using C# 3.0 or Visual Studio 2008, you don't need the code in this article. Just use LinqBridge.
C#3.0のLinq(言語統合クエリ)は、1度触れるとやみつきになってしまうくらい面白い。
しかし、われわれの中には理由はともあれVisual Studio 2005を使い続けている人もいるだろう。
私の場合は、$550払ってVS2008 Proにアップグレードするのももったいないが、かといってVisual C# Express EditionやSharpDevelopに変更することにより、マクロやコードダイアグラムなどの機能を失ってしまうのも惜しい。そこで、C#2.0でもLinq-to-Objectsを利用できるようにする方法を考えてみた。
注意:
.NET Framework 2.0を使い続けていたとしても、C#3.0やVisualStudio2008が使用できるのであれば、この記事のやり方ではなく、LinqBridgeを使うことができる。
http://www.albahari.com/nutshell/linqbridge.html
Linqを使用した場合
using System; using System.Linq; class Program { static void Main(string[] args) { string[] words = new string[] { "Pies", "Are", "Good", "In", "Lovely", "Apples" }; // Pies Are Good Console.WriteLine(string.Join(" ", words.Take(3).ToArray())); // Apples Are Good In Lovely Pies Console.WriteLine(string.Join(" ", words.OrderBy(x => x).ToArray())); int[] numbers = new int[] { 4, 95, 309, 357, 233, 2 }; // 1000 Console.WriteLine(numbers.Sum()); // 666 Console.WriteLine((from x in numbers where x > 300 select x).Sum()); } }
PoorMan's Linqの場合
using System; using System.Collections.Generic; using Compatibility.Linq; class Program { public static void Main(string[] args) { string[] words = new string[] { "Pies", "Are", "Good", "In", "Lovely", "Apples" }; // Pies Are Good Console.WriteLine(string.Join(" ", Linq(words).Take(3).ToArray())); // Apples Are Good In Lovely Pies Console.WriteLine(string.Join(" ", Linq(words).Sorted().ToArray())); int[] numbers = new int[] { 4, 95, 309, 357, 233, 2 }; // 1000 Console.WriteLine(Enumerable.Sum(numbers)); // 666 Console.WriteLine(Enumerable.Sum(Linq(numbers) .Where(delegate(int x) { return x > 300; }))); } static PoorMansLinq<T> Linq<T>(IEnumerable<T> source) { return new PoorMansLinq<T>(source); } }
詳細は、上記のサイトを参照