.NET 3.5のLinqを実際に動かす
Visual C#2008 Beta2に入れかえたので、C#3.0のLinqコードを、どれだけ可用になるかみるため、実際にコンパイルしてみた。
C#3.0のcscは c:\Windows\Microsoft.NET\Framework\v3.5\csc.exe にある。
Linq1.cs
using System; using System.Linq; class Linq1 { static void Main() { var al = new int[] {1, 2, 3, 4, 5, 6, 7}; foreach (var o in from n in al where n % 2 == 0 select n) { Console.WriteLine(o); } } }
ビルド&実行
$ csc Linq1.cs Microsoft (R) Visual C# 2008 Compiler Beta 2 version 3.05.20706.1 for Microsoft (R) .NET Framework version 3.5 Copyright (C) Microsoft Corporation. All rights reserved. $ ./Linq1.exe 2 4 6
所見
- using System.Linq; は配列等にもLinqする(って用語でいいのかな)ためには必須
- System.Core.dll にある
- (from n in al where n % 2 == 0 select n) の戻り値は System.Collections.Generic.IEnumerable として扱う
- varで受けるのが普通になりそう
Linq2.cs
using System; using System.Linq; class Linq2 { static void Main() { var al = new int[] {1, 2, 3, 4, 5, 6, 7}; var en = from n in al where n % 2 == 0 select n; var il = (int[]) en; Console.WriteLine(il.GetType()); } }
実行
$ csc Linq2.cs Microsoft (R) Visual C# 2008 Compiler Beta 2 version 3.05.20706.1 for Microsoft (R) .NET Framework version 3.5 Copyright (C) Microsoft Corporation. All rights reserved. $ ./Linq2.exe ハンドルされていない例外: System.InvalidCastException: 型 '<WhereIterator>d__0`1[System.Int32]' のオブジェクトを型 'System.Int32[]' にキャストできません。 場所 Linq2.Main()
- あらら
- var il = new List
(en).ToArray(); ならOK
- var il = new List
Linq3.cs
using System; using System.Linq; class Linq3 { static void Main() { Func<int, bool> func = n => n % 2 == 0; Console.WriteLine(new int[] {1, 2, 3, 4}.Any(func)); } }
- この形式のFunc(lambda expression)はvarで受けられない。
- Anyはひとつでも要素が関数を満たせば、Trueを返す
参考
おまけ
Linq0.cs
using System; using System.Linq; class Linq0 { static void Main() { int var = 0; Console.WriteLine(var); int from = 0; Console.WriteLine(from); int where = 0; Console.WriteLine(where); int select = 0; Console.WriteLine(select); } }
$ csc Linq0.cs Microsoft (R) Visual C# 2008 Compiler Beta 2 version 3.05.20706.1 for Microsoft (R) .NET Framework version 3.5 Copyright (C) Microsoft Corporation. All rights reserved. $ ./Linq0.exe 0 0 0 0