Movatterモバイル変換


[0]ホーム

URL:


Fujio Kojima, profile picture
Uploaded byFujio Kojima
PPTX, PDF19,643 views

C# 式木 (Expression Tree) ~ LINQをより深く理解するために ~

Hokuriku.NET C# 勉強会「C# 式木 (Expression Tree) ~ LINQをより深く理解するために ~」https://atnd.org/events/57085で使用した資料に加筆1. LINQ to Objects 復習2. IQueryable<t>3. 式木 (Expression Tree)4. 式木メタ プログラミング5. LINQ プロバイダー

Embed presentation

Downloaded 47 times
https://atnd.org/events/57085
• • • http://blog.shos.info • •
• http://slidesha.re/1tA0Tit • http://1drv.ms/1zs3n78 3 ソースコード 参照
•
1. 2. 3. 4. 5.
• IEnumerable<int> sequence1 = new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; IEnumerable<int> sequence2 = sequence1.Where (x => x % 2 == 0); IEnumerable<int> sequence3 = sequence2.Select (x => x * x ); foreach (int item in sequence3) Console.WriteLine(item); ソースコード 参照
•
• ソースコード 参照 IEnumerable<int> sequence1 = new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; IEnumerable<int> sequence2 = sequence1.Where (x => x % 2 == 0); IEnumerable<int> sequence3 = sequence2.Select (x => x * x ); foreach (int item in sequence3) Console.WriteLine(item); 実際にsequence3 から値が取り出さ れるまで、sequence1 から値は取り 出されず、Where やSelect に渡した デリゲートも実行されない
• var data = new EmployeeDataClassesDataContext(); data.Log = Console.Out; var sequence1 = data.Employee; var sequence2 = sequence1.Where ( ソースコード 参照 employee => employee.Name.Contains("田") ); var sequence3 = sequence2.Select ( employee => new { 番号= employee.Id, 名前= employee.Name }); foreach (var employee in sequence3) Console.WriteLine("{0}: {1}", employee.番号, employee.名前);
• SELECT [t0].[Id], [t0].[Name] FROM [dbo].[Employee] AS [t0] • SELECT [t0].[Id] AS [番号], [t0].[Name] AS [名前] FROM [dbo].[Employee] AS [t0] WHERE [t0].[Name] LIKE @p0 -- @p0: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [%田%]
• public static class Enumerable { public static class Queryable { public static IQueryable<T> Where<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate); } public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, int, bool> predicate); } •
• • •
• class Program { static void Main() { ソースコード Func<int, int, int> sequence1 = (x, y) => x + y; Func<int, int, int> sequence2 = (x, y) => { return x + y; }; Expression<Func<int, int, int>> expression1 = (x, y) => x + y; //Expression<Func<int, int, int>> expression2 = (x, y) => { return x + y; }; } } ブロックが含まれるラムダ式は式として扱えない (IQueryable<T> には使えない) 参照
• • var sequence4 = from employee in data.Employee where employee.Name.Contains("田") select new { 番号= employee.Id, 名前= employee.Name };
• •
• • http://msdn.microsoft.com/ja-jp/library/system.linq.iqueryable(v=vs.110).aspx public interface IQueryable : IEnumerable { Type ElementType { get; } Expression Expression { get; } IQueryProvider Provider { get; } } public interface IQueryable<T> : IEnumerable<T>, IQueryable {}
• class Foo : IQueryable { public Type ElementType { get { throw new NotImplementedException(); } } public Expression Expression { get { throw new NotImplementedException(); } } public IQueryProvider Provider { get { throw new NotImplementedException(); } } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } ソースコード 参照
• ソースコード 参照 Expression<Func<int, int, int>> expression = (x, y) => x + y; ((Expression)expression).Show();
•
•
•
•
•
• • • • • Assembly Module Type ・Class ・Interface ・Value Type FieldInfo PropertyInfo EventInfo MethodInfo ConstructorInfo ParameterInfo
• • • •
• • •
• • • • • •
• • • •
• • • CodeDOM CodeDOMProvider ソースコード (C#、VB、JScript) アセンブリ GenerateCodeFromNamespace CompileAssemblyFromDom
• • • •
• namespace CodeDomHelloWorldDemo { using System; class Program { static void Main() { Console.WriteLine("Hello world!"); Console.ReadKey(); } } } ソースコード 参照
• • • • http://msdn.microsoft.com/ja-jp/library/f7dy01k1(v=vs.110).aspx
• •
Expression<Func<Employee, bool>> expression = employee => employee.Name.Contains("山"); Parameters Body Object Method Arguments Expression Member employee => employee.Name.Con tains("山") employee.Name Contains employee Name “山” employee employee.Name.Co ntains("山")
• 1. 2. + => x y (x, y)
• Expression の派生クラス一覧- 継承階層- Expression クラス- MSDN ライブラリ
パラメーターのx とy は、(x, y) 部分 とx + y 部分で使われているが、 それぞれ1 インスタンスずつにする
• static Func<int, int, int> AddByExpression() { // 生成したい式 // (int x, int y) => x + y // 引数x の式 var x = Expression.Parameter(type: typeof(int)); // 引数y の式 var y = Expression.Parameter(type: typeof(int)); // x + y の式 var add = Expression.Add (left: x, right: y); // (x, y) => x + y の式 var lambda = Expression.Lambda (add, x, y ); // ラムダ式をコンパイルしてデリゲートとして返す return (Func<int, int, int>)lambda.Compile(); } ソースコード 参照
• static Func<int, int, int> AddByExpression() { // 生成したい式 // (int x, int y) => x + y // 引数x の式 var x = Expression.Parameter(type: typeof(int)); // 引数y の式 var y = Expression.Parameter(type: typeof(int)); // x + y の式 var add = Expression.Add (left: x, right: y); // (x, y) => x + y の式 var lambda = Expression.Lambda (add, x, y ); // ラムダ式をコンパイルしてデリゲートとして返す return (Func<int, int, int>)lambda.Compile(); } ソースコード 参照
• 1. 2. 3. • 1. 2. 3. 4.
•
•
• // Expression (式) によるメソッド呼び出しメソッドの生成 static Func<T, TResult> CallByExpression<T, TResult>(string methodName) { // 生成したい式の例: // (T item) => item.methodName() // 引数item の式 var parameterExpression = Expression.Parameter(type: typeof(T), name: "item"); // item.methodName() の式 var callExpression = Expression.Call( instance: parameterExpression, method : typeof(T).GetMethod(methodName, Type.EmptyTypes) ); // item => item.methodName() の式 var lambda = Expression.Lambda(callExpression, parameterExpression); // ラムダ式をコンパイルしてデリゲートとして返す return (Func<T, TResult>)lambda.Compile(); } ソースコード 参照
• •
• 1. 2.
• 1. 2. 1. 2. 3. 1. 2. 3. 4. 1. 2. 3.
•
•
• • • • • http://blog.jhashimoto.net/entry/20120616/1339806360
• • http://msdn.microsoft.com/ja-jp/library/bb546158.aspx • • http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx • • http://weblogs.asp.net/mehfuzh/writing-custom-linq-provider
LINQプロバイダー (IQueryProvider) クエリーコンテキスト 式 クエリー (IQueryable) 式を解釈
• • • •
• ソースコード pubic class QueryProvider : IQueryProvider { public IQueryable<TCollection> CreateQuery<TCollection>(Expression expression) { return new QueryableData<TCollection>(this, expression); } IQueryable IQueryProvider.CreateQuery(Expression expression) { return null; } public TResult Execute<TResult>(Expression expression) { return default(TResult); } public object Execute(Expression expression) { // ここで式木を解釈して、IEnumerable を作って返す } } 参照
• • •
• static void Main() { IQueryable<int> query1 = new QueryableData<int>(new QueryProvider()); Console.WriteLine(query1.Expression); IQueryable<int> query2 = query1.Where(x => x % 2 == 0); Console.WriteLine(query2.Expression); IQueryable<int> query3 = query2.OrderBy(x => x); Console.WriteLine(query3.Expression); IQueryable<int> query4 = query3.Select(x => x * x); Console.WriteLine(query4.Expression); foreach (int item in query4) Console.WriteLine(item); } ソースコード 参照
• value(ProviderSample.QueryableData`1[System.Int32]) value(ProviderSample.QueryableData`1[System.Int32]).Where(x => ((x % 2) == 0)) value(ProviderSample.QueryableData`1[System.Int32]).Where(x => ((x % 2) == 0)).OrderBy(x => x) value(ProviderSample.QueryableData`1[System.Int32]).Where(x => ((x % 2) == 0)).OrderBy(x => x).Select(x => (x * x)) 1 1 2 3 5 8 13 21 34
• •
• public class MyExpressionVisitor : ExpressionVisitor { protected override Expression VisitBinary(BinaryExpression expression) { return base.VisitBinary(expression); } protected override Expression VisitConstant(ConstantExpression expression) { return base.VisitConstant(expression); } protected override Expression VisitMethodCall(MethodCallExpression expression) { return base.VisitMethodCall(expression); } protected override Expression VisitParameter(ParameterExpression expression) { return base.VisitParameter(expression); } …… 等々…… } ソースコード 参照
• ☆式(x, y) => x + y 二項演算((x + y)) - 右辺: x, 左辺: y, 型: System.Int32 引数(x) - 名前: x, 型: System.Int32 引数(y) - 名前: y, 型: System.Int32 引数(x) - 名前: x, 型: System.Int32 引数(y) - 名前: y, 型: System.Int32 ☆式text => text.Contains("福") メソッドコール(text.Contains("福")) - メソッド名: Contains, 型: System.Boolean 引数(text) - 名前: text, 型: System.String 定数("福") - 値: 福, 型: System.String 引数(text) - 名前: text, 型: System.String
• public class QueryableTimeline<TElement> : IOrderedQueryable<TElement> { public IQueryProvider Provider { get; private set; } public Expression Expression { get; private set; } public Type ElementType { get { return typeof(TElement); } } public QueryableTimeline() { Provider = new TimelineQueryProvider(); Expression = Expression.Constant(this); } …… 途中省略…… } ソースコード 参照
•

Recommended

PDF
基礎線形代数講座
PDF
モジュールの凝集度・結合度・インタフェース
PDF
マルチコアを用いた画像処理
PDF
CUDAプログラミング入門
PDF
自己教師学習(Self-Supervised Learning)
PDF
プログラムを高速化する話
PPTX
近年のHierarchical Vision Transformer
PDF
がんばらなくても C# で Single Page Web アプリケーションが書けてしまう「Blazor」とは
PDF
ChatGPT 人間のフィードバックから強化学習した対話AI
PPTX
Deep Learning による視覚×言語融合の最前線
PDF
SSII2022 [TS1] Transformerの最前線〜 畳込みニューラルネットワークの先へ 〜
 
PDF
機械学習による統計的実験計画(ベイズ最適化を中心に)
PDF
ARM CPUにおけるSIMDを用いた高速計算入門
PDF
Teslaにおけるコンピュータビジョン技術の調査
PDF
オススメのJavaログ管理手法 ~コンテナ編~(Open Source Conference 2022 Online/Spring 発表資料)
PDF
組み込み関数(intrinsic)によるSIMD入門
PDF
オブジェクト指向プログラミングの現在・過去・未来
PDF
Pythonによる黒魔術入門
PPTX
ちゃんとした C# プログラムを書けるようになる実践的な方法~ Visual Studio を使った 高品質・低コスト・保守性の高い開発
PDF
【論文読み会】Deep Clustering for Unsupervised Learning of Visual Features
PDF
型安全性入門
PDF
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
PDF
PlaySQLAlchemy: SQLAlchemy入門
PPTX
Effective Modern C++ 勉強会 Item 22
PPTX
PyTorchLightning ベース Hydra+MLFlow+Optuna による機械学習開発環境の構築
PPTX
DockerコンテナでGitを使う
PDF
[DL輪読会]Learning Transferable Visual Models From Natural Language Supervision
PDF
マイクロにしすぎた結果がこれだよ!
PDF
ADO.NETとORMとMicro-ORM -dapper dot netを使ってみた
PPTX
C# 6.0 Preview

More Related Content

PDF
基礎線形代数講座
PDF
モジュールの凝集度・結合度・インタフェース
PDF
マルチコアを用いた画像処理
PDF
CUDAプログラミング入門
PDF
自己教師学習(Self-Supervised Learning)
PDF
プログラムを高速化する話
PPTX
近年のHierarchical Vision Transformer
PDF
がんばらなくても C# で Single Page Web アプリケーションが書けてしまう「Blazor」とは
基礎線形代数講座
モジュールの凝集度・結合度・インタフェース
マルチコアを用いた画像処理
CUDAプログラミング入門
自己教師学習(Self-Supervised Learning)
プログラムを高速化する話
近年のHierarchical Vision Transformer
がんばらなくても C# で Single Page Web アプリケーションが書けてしまう「Blazor」とは

What's hot

PDF
ChatGPT 人間のフィードバックから強化学習した対話AI
PPTX
Deep Learning による視覚×言語融合の最前線
PDF
SSII2022 [TS1] Transformerの最前線〜 畳込みニューラルネットワークの先へ 〜
 
PDF
機械学習による統計的実験計画(ベイズ最適化を中心に)
PDF
ARM CPUにおけるSIMDを用いた高速計算入門
PDF
Teslaにおけるコンピュータビジョン技術の調査
PDF
オススメのJavaログ管理手法 ~コンテナ編~(Open Source Conference 2022 Online/Spring 発表資料)
PDF
組み込み関数(intrinsic)によるSIMD入門
PDF
オブジェクト指向プログラミングの現在・過去・未来
PDF
Pythonによる黒魔術入門
PPTX
ちゃんとした C# プログラムを書けるようになる実践的な方法~ Visual Studio を使った 高品質・低コスト・保守性の高い開発
PDF
【論文読み会】Deep Clustering for Unsupervised Learning of Visual Features
PDF
型安全性入門
PDF
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
PDF
PlaySQLAlchemy: SQLAlchemy入門
PPTX
Effective Modern C++ 勉強会 Item 22
PPTX
PyTorchLightning ベース Hydra+MLFlow+Optuna による機械学習開発環境の構築
PPTX
DockerコンテナでGitを使う
PDF
[DL輪読会]Learning Transferable Visual Models From Natural Language Supervision
PDF
マイクロにしすぎた結果がこれだよ!
ChatGPT 人間のフィードバックから強化学習した対話AI
Deep Learning による視覚×言語融合の最前線
SSII2022 [TS1] Transformerの最前線〜 畳込みニューラルネットワークの先へ 〜
 
機械学習による統計的実験計画(ベイズ最適化を中心に)
ARM CPUにおけるSIMDを用いた高速計算入門
Teslaにおけるコンピュータビジョン技術の調査
オススメのJavaログ管理手法 ~コンテナ編~(Open Source Conference 2022 Online/Spring 発表資料)
組み込み関数(intrinsic)によるSIMD入門
オブジェクト指向プログラミングの現在・過去・未来
Pythonによる黒魔術入門
ちゃんとした C# プログラムを書けるようになる実践的な方法~ Visual Studio を使った 高品質・低コスト・保守性の高い開発
【論文読み会】Deep Clustering for Unsupervised Learning of Visual Features
型安全性入門
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
PlaySQLAlchemy: SQLAlchemy入門
Effective Modern C++ 勉強会 Item 22
PyTorchLightning ベース Hydra+MLFlow+Optuna による機械学習開発環境の構築
DockerコンテナでGitを使う
[DL輪読会]Learning Transferable Visual Models From Natural Language Supervision
マイクロにしすぎた結果がこれだよ!

Viewers also liked

PDF
ADO.NETとORMとMicro-ORM -dapper dot netを使ってみた
PPTX
C# 6.0 Preview
PDF
よろしい、ならばMicro-ORMだ
PDF
Final LINQ Extensions
PPTX
C# 3.0 以降
PPTX
メタプログラミング C#
PPTX
3D で遊ぼう ~C#er も TypeScript で楽々 WebGL~
PPTX
Windows アプリケーション開発 はじめに ~ Windows アプリケーション開発初学者の方向け Visual Studio を使ったアプリケーショ...
PPTX
Windows 8 ストア アプリ 開発 Tips
PDF
You will be assimilated. Resistance is futile.
PPTX
C# MVP に聞くC#アレコレ! 小島の分
PPTX
.NET MVP によるドキドキ・ライブコーディング! 小島の分
DOCX
Bodlogiin code
 
PDF
Visual Studio 2017 RC C# まわり
PPTX
Xamarin ~ iOS/Android/Windows アプリを C# で作ろう~
PPTX
2014 08-30 life with roslyn
PDF
Final LINQ Extensions II
PDF
Final LINQ extensions III
PPTX
Windows phoneの開発ツール
PDF
式の体を成して無い式を式の体を成すように式と式木で何とかする式
ADO.NETとORMとMicro-ORM -dapper dot netを使ってみた
C# 6.0 Preview
よろしい、ならばMicro-ORMだ
Final LINQ Extensions
C# 3.0 以降
メタプログラミング C#
3D で遊ぼう ~C#er も TypeScript で楽々 WebGL~
Windows アプリケーション開発 はじめに ~ Windows アプリケーション開発初学者の方向け Visual Studio を使ったアプリケーショ...
Windows 8 ストア アプリ 開発 Tips
You will be assimilated. Resistance is futile.
C# MVP に聞くC#アレコレ! 小島の分
.NET MVP によるドキドキ・ライブコーディング! 小島の分
Bodlogiin code
 
Visual Studio 2017 RC C# まわり
Xamarin ~ iOS/Android/Windows アプリを C# で作ろう~
2014 08-30 life with roslyn
Final LINQ Extensions II
Final LINQ extensions III
Windows phoneの開発ツール
式の体を成して無い式を式の体を成すように式と式木で何とかする式

Similar to C# 式木 (Expression Tree) ~ LINQをより深く理解するために ~

PPTX
Linqの速度測ってみた
PPTX
C#を始めたばかりの人へのLINQ to Objects
PDF
An Internal of LINQ to Objects
PPTX
C# LINQ ~深く知って、使いまくろう~
PDF
C#勉強会 ~ C#9の新機能 ~
PDF
VS勉強会 .NET Framework 入門
PDF
LINQ in Unity
PDF
LINQソースでGO!
PPTX
【java8 勉強会】 怖くない!ラムダ式, Stream API
PPTX
Linqことはじめ
PPTX
C# LINQ入門
PPTX
LINQ概要
PPTX
LINQ 概要 + 結構便利な LINQ to XML
PPTX
LINQ の概要とかもろもろ
PDF
これからの「言語」の話をしよう ―― 未来を生きるためのツール
PDF
MlnagoyaRx
ODP
F#とC#で見る関数志向プログラミング
PDF
Linq To Fun
 
PPTX
Visual Studio による開発環境・プログラミングの進化
PPTX
超LINQ入門
 
Linqの速度測ってみた
C#を始めたばかりの人へのLINQ to Objects
An Internal of LINQ to Objects
C# LINQ ~深く知って、使いまくろう~
C#勉強会 ~ C#9の新機能 ~
VS勉強会 .NET Framework 入門
LINQ in Unity
LINQソースでGO!
【java8 勉強会】 怖くない!ラムダ式, Stream API
Linqことはじめ
C# LINQ入門
LINQ概要
LINQ 概要 + 結構便利な LINQ to XML
LINQ の概要とかもろもろ
これからの「言語」の話をしよう ―― 未来を生きるためのツール
MlnagoyaRx
F#とC#で見る関数志向プログラミング
Linq To Fun
 
Visual Studio による開発環境・プログラミングの進化
超LINQ入門
 

More from Fujio Kojima

PDF
.NETラボ 勉強会 2021年1月 「C#で機械学習」
PPTX
C# でニューラルネットワークをスクラッチで書いて機械学習の原理を理解しよう
PDF
.NET 6 時代のデスクトップ アプリケーション開発
PDF
機械学習 (AI/ML) 勉強会 #1 基本編
PDF
C#の新機能勉強会 ~ C#7、8の新機能を活用して速く安全なプログラムを書こう~
PDF
C# ドキドキ ライブ コーディング!! ~ 小島の分 ~ | BuriKaigi 2020
PDF
[C#/.NET] ITエンジニア (Developer) 向け AIエージェント開発ハンズオンセミナー
PDF
AIエージェント勉強会~マイクロソフトの最新技術発表を受けて~ (2025/07)
PDF
Burikaigi 2023「C# Live Coding!」 小島の分
PDF
.NET 5 勉強会 ~.NET Framework から .NET へ~
PPTX
機械学習入門
PDF
『機械学習 (AI/ML) の基礎と Microsoft の AI | 2019/04/02 Global AI Nights Fukui
PDF
ITエンジニア (Developer) 向けAIエージェント勉強会 (2025/06/13)
PPTX
BuriKaigi2019 「C# ドキドキ・ライブコーディング」 小島の分
PDF
『議論パターン』 (Discussion Patterns) ~不毛な議論を避け、実り有る議論とするために~
PPTX
「ふくいソフトウェアコンペティション 2014 大賞受賞者プレゼンテーション」
PDF
2022.04.23 .NET 6 -7 時代のデスクトップ アプリケーション開発
PDF
機械学習 (AI/ML) 勉強会 #2 IoT編
PDF
牛タン会議 2019 @ 仙台 「C# ドキドキ ライブ!!」 小島の分
PDF
BuriKaigi 2022 「C# Live Coding!」 小島の分
.NETラボ 勉強会 2021年1月 「C#で機械学習」
C# でニューラルネットワークをスクラッチで書いて機械学習の原理を理解しよう
.NET 6 時代のデスクトップ アプリケーション開発
機械学習 (AI/ML) 勉強会 #1 基本編
C#の新機能勉強会 ~ C#7、8の新機能を活用して速く安全なプログラムを書こう~
C# ドキドキ ライブ コーディング!! ~ 小島の分 ~ | BuriKaigi 2020
[C#/.NET] ITエンジニア (Developer) 向け AIエージェント開発ハンズオンセミナー
AIエージェント勉強会~マイクロソフトの最新技術発表を受けて~ (2025/07)
Burikaigi 2023「C# Live Coding!」 小島の分
.NET 5 勉強会 ~.NET Framework から .NET へ~
機械学習入門
『機械学習 (AI/ML) の基礎と Microsoft の AI | 2019/04/02 Global AI Nights Fukui
ITエンジニア (Developer) 向けAIエージェント勉強会 (2025/06/13)
BuriKaigi2019 「C# ドキドキ・ライブコーディング」 小島の分
『議論パターン』 (Discussion Patterns) ~不毛な議論を避け、実り有る議論とするために~
「ふくいソフトウェアコンペティション 2014 大賞受賞者プレゼンテーション」
2022.04.23 .NET 6 -7 時代のデスクトップ アプリケーション開発
機械学習 (AI/ML) 勉強会 #2 IoT編
牛タン会議 2019 @ 仙台 「C# ドキドキ ライブ!!」 小島の分
BuriKaigi 2022 「C# Live Coding!」 小島の分

C# 式木 (Expression Tree) ~ LINQをより深く理解するために ~

  • 1.
  • 2.
    • • •http://blog.shos.info • •
  • 3.
    • http://slidesha.re/1tA0Tit •http://1drv.ms/1zs3n78 3 ソースコード 参照
  • 4.
  • 5.
  • 7.
    • IEnumerable<int> sequence1= new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; IEnumerable<int> sequence2 = sequence1.Where (x => x % 2 == 0); IEnumerable<int> sequence3 = sequence2.Select (x => x * x ); foreach (int item in sequence3) Console.WriteLine(item); ソースコード 参照
  • 8.
  • 9.
    • ソースコード 参照IEnumerable<int> sequence1 = new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; IEnumerable<int> sequence2 = sequence1.Where (x => x % 2 == 0); IEnumerable<int> sequence3 = sequence2.Select (x => x * x ); foreach (int item in sequence3) Console.WriteLine(item); 実際にsequence3 から値が取り出さ れるまで、sequence1 から値は取り 出されず、Where やSelect に渡した デリゲートも実行されない
  • 11.
    • var data= new EmployeeDataClassesDataContext(); data.Log = Console.Out; var sequence1 = data.Employee; var sequence2 = sequence1.Where ( ソースコード 参照 employee => employee.Name.Contains("田") ); var sequence3 = sequence2.Select ( employee => new { 番号= employee.Id, 名前= employee.Name }); foreach (var employee in sequence3) Console.WriteLine("{0}: {1}", employee.番号, employee.名前);
  • 12.
    • SELECT [t0].[Id],[t0].[Name] FROM [dbo].[Employee] AS [t0] • SELECT [t0].[Id] AS [番号], [t0].[Name] AS [名前] FROM [dbo].[Employee] AS [t0] WHERE [t0].[Name] LIKE @p0 -- @p0: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [%田%]
  • 13.
    • public staticclass Enumerable { public static class Queryable { public static IQueryable<T> Where<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate); } public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, int, bool> predicate); } •
  • 14.
  • 15.
    • class Program{ static void Main() { ソースコード Func<int, int, int> sequence1 = (x, y) => x + y; Func<int, int, int> sequence2 = (x, y) => { return x + y; }; Expression<Func<int, int, int>> expression1 = (x, y) => x + y; //Expression<Func<int, int, int>> expression2 = (x, y) => { return x + y; }; } } ブロックが含まれるラムダ式は式として扱えない (IQueryable<T> には使えない) 参照
  • 16.
    • • varsequence4 = from employee in data.Employee where employee.Name.Contains("田") select new { 番号= employee.Id, 名前= employee.Name };
  • 17.
  • 18.
    • • http://msdn.microsoft.com/ja-jp/library/system.linq.iqueryable(v=vs.110).aspxpublic interface IQueryable : IEnumerable { Type ElementType { get; } Expression Expression { get; } IQueryProvider Provider { get; } } public interface IQueryable<T> : IEnumerable<T>, IQueryable {}
  • 19.
    • class Foo: IQueryable { public Type ElementType { get { throw new NotImplementedException(); } } public Expression Expression { get { throw new NotImplementedException(); } } public IQueryProvider Provider { get { throw new NotImplementedException(); } } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } ソースコード 参照
  • 21.
    • ソースコード 参照Expression<Func<int, int, int>> expression = (x, y) => x + y; ((Expression)expression).Show();
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 28.
    • • •• • Assembly Module Type ・Class ・Interface ・Value Type FieldInfo PropertyInfo EventInfo MethodInfo ConstructorInfo ParameterInfo
  • 30.
  • 31.
  • 32.
    • • •• • •
  • 33.
  • 35.
    • • •CodeDOM CodeDOMProvider ソースコード (C#、VB、JScript) アセンブリ GenerateCodeFromNamespace CompileAssemblyFromDom
  • 36.
  • 37.
    • namespace CodeDomHelloWorldDemo{ using System; class Program { static void Main() { Console.WriteLine("Hello world!"); Console.ReadKey(); } } } ソースコード 参照
  • 38.
    • • •• http://msdn.microsoft.com/ja-jp/library/f7dy01k1(v=vs.110).aspx
  • 39.
  • 40.
    Expression<Func<Employee, bool>> expression= employee => employee.Name.Contains("山"); Parameters Body Object Method Arguments Expression Member employee => employee.Name.Con tains("山") employee.Name Contains employee Name “山” employee employee.Name.Co ntains("山")
  • 42.
    • 1. 2.+ => x y (x, y)
  • 43.
    • Expression の派生クラス一覧-継承階層- Expression クラス- MSDN ライブラリ
  • 44.
    パラメーターのx とy は、(x,y) 部分 とx + y 部分で使われているが、 それぞれ1 インスタンスずつにする
  • 45.
    • static Func<int,int, int> AddByExpression() { // 生成したい式 // (int x, int y) => x + y // 引数x の式 var x = Expression.Parameter(type: typeof(int)); // 引数y の式 var y = Expression.Parameter(type: typeof(int)); // x + y の式 var add = Expression.Add (left: x, right: y); // (x, y) => x + y の式 var lambda = Expression.Lambda (add, x, y ); // ラムダ式をコンパイルしてデリゲートとして返す return (Func<int, int, int>)lambda.Compile(); } ソースコード 参照
  • 46.
    • static Func<int,int, int> AddByExpression() { // 生成したい式 // (int x, int y) => x + y // 引数x の式 var x = Expression.Parameter(type: typeof(int)); // 引数y の式 var y = Expression.Parameter(type: typeof(int)); // x + y の式 var add = Expression.Add (left: x, right: y); // (x, y) => x + y の式 var lambda = Expression.Lambda (add, x, y ); // ラムダ式をコンパイルしてデリゲートとして返す return (Func<int, int, int>)lambda.Compile(); } ソースコード 参照
  • 47.
    • 1. 2.3. • 1. 2. 3. 4.
  • 48.
  • 49.
  • 50.
    • // Expression(式) によるメソッド呼び出しメソッドの生成 static Func<T, TResult> CallByExpression<T, TResult>(string methodName) { // 生成したい式の例: // (T item) => item.methodName() // 引数item の式 var parameterExpression = Expression.Parameter(type: typeof(T), name: "item"); // item.methodName() の式 var callExpression = Expression.Call( instance: parameterExpression, method : typeof(T).GetMethod(methodName, Type.EmptyTypes) ); // item => item.methodName() の式 var lambda = Expression.Lambda(callExpression, parameterExpression); // ラムダ式をコンパイルしてデリゲートとして返す return (Func<T, TResult>)lambda.Compile(); } ソースコード 参照
  • 51.
  • 52.
  • 53.
    • 1. 2.1. 2. 3. 1. 2. 3. 4. 1. 2. 3.
  • 54.
  • 55.
  • 58.
    • • •• • http://blog.jhashimoto.net/entry/20120616/1339806360
  • 59.
    • • http://msdn.microsoft.com/ja-jp/library/bb546158.aspx• • http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx • • http://weblogs.asp.net/mehfuzh/writing-custom-linq-provider
  • 60.
  • 61.
  • 62.
    • ソースコード pubicclass QueryProvider : IQueryProvider { public IQueryable<TCollection> CreateQuery<TCollection>(Expression expression) { return new QueryableData<TCollection>(this, expression); } IQueryable IQueryProvider.CreateQuery(Expression expression) { return null; } public TResult Execute<TResult>(Expression expression) { return default(TResult); } public object Execute(Expression expression) { // ここで式木を解釈して、IEnumerable を作って返す } } 参照
  • 63.
  • 64.
    • static voidMain() { IQueryable<int> query1 = new QueryableData<int>(new QueryProvider()); Console.WriteLine(query1.Expression); IQueryable<int> query2 = query1.Where(x => x % 2 == 0); Console.WriteLine(query2.Expression); IQueryable<int> query3 = query2.OrderBy(x => x); Console.WriteLine(query3.Expression); IQueryable<int> query4 = query3.Select(x => x * x); Console.WriteLine(query4.Expression); foreach (int item in query4) Console.WriteLine(item); } ソースコード 参照
  • 65.
    • value(ProviderSample.QueryableData`1[System.Int32]) value(ProviderSample.QueryableData`1[System.Int32]).Where(x=> ((x % 2) == 0)) value(ProviderSample.QueryableData`1[System.Int32]).Where(x => ((x % 2) == 0)).OrderBy(x => x) value(ProviderSample.QueryableData`1[System.Int32]).Where(x => ((x % 2) == 0)).OrderBy(x => x).Select(x => (x * x)) 1 1 2 3 5 8 13 21 34
  • 66.
  • 67.
    • public classMyExpressionVisitor : ExpressionVisitor { protected override Expression VisitBinary(BinaryExpression expression) { return base.VisitBinary(expression); } protected override Expression VisitConstant(ConstantExpression expression) { return base.VisitConstant(expression); } protected override Expression VisitMethodCall(MethodCallExpression expression) { return base.VisitMethodCall(expression); } protected override Expression VisitParameter(ParameterExpression expression) { return base.VisitParameter(expression); } …… 等々…… } ソースコード 参照
  • 68.
    • ☆式(x, y)=> x + y 二項演算((x + y)) - 右辺: x, 左辺: y, 型: System.Int32 引数(x) - 名前: x, 型: System.Int32 引数(y) - 名前: y, 型: System.Int32 引数(x) - 名前: x, 型: System.Int32 引数(y) - 名前: y, 型: System.Int32 ☆式text => text.Contains("福") メソッドコール(text.Contains("福")) - メソッド名: Contains, 型: System.Boolean 引数(text) - 名前: text, 型: System.String 定数("福") - 値: 福, 型: System.String 引数(text) - 名前: text, 型: System.String
  • 69.
    • public classQueryableTimeline<TElement> : IOrderedQueryable<TElement> { public IQueryProvider Provider { get; private set; } public Expression Expression { get; private set; } public Type ElementType { get { return typeof(TElement); } } public QueryableTimeline() { Provider = new TimelineQueryProvider(); Expression = Expression.Constant(this); } …… 途中省略…… } ソースコード 参照
  • 70.

[8]ページ先頭

©2009-2025 Movatter.jp