Skip to content

Instantly share code, notes, and snippets.

@pleonex
Created November 9, 2015 00:30
Show Gist options
  • Save pleonex/ef71081d55bbdd08e560 to your computer and use it in GitHub Desktop.
Save pleonex/ef71081d55bbdd08e560 to your computer and use it in GitHub Desktop.
Simple Lambda2SQL converter
//
// Program.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Linq.Expressions;
namespace LambdaParser
{
public static class Program
{
private class A
{
public int X { get; set; }
public int Y { get; set; }
}
public static void Main()
{
Expression<Func<A, int, bool>> expression = (a, p1) => a.X == 42 && a.Y == (a.X + p1);
Console.WriteLine(PrintExpression(expression.Body));
}
private static string PrintExpression(Expression expression)
{
if (expression.NodeType == ExpressionType.MemberAccess)
return (expression as MemberExpression).Member.Name;
if (expression.NodeType == ExpressionType.Constant)
return (expression as ConstantExpression).Value.ToString();
if (expression.NodeType == ExpressionType.Parameter)
return "%" + (Convert.ToInt32((expression as ParameterExpression).Name.Substring(1)) - 1);
BinaryExpression expr = expression as BinaryExpression;
string result = "(" + PrintExpression2(expr.Left);
if (expression.NodeType == ExpressionType.Equal)
result += " == ";
if (expression.NodeType == ExpressionType.AndAlso)
result += " AND ";
if (expression.NodeType == ExpressionType.Add)
result += "+";
return result + PrintExpression2(expr.Right) + ")";
}
}
}
@pleonex
Copy link
Author

pleonex commented Nov 9, 2015

The output is: ((X == 42) AND (Y == (X+%0)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment