And I mean this in the easiest way. Say you have a function with the following signature:
public static Expression<Func<T, bool>> CreateExpression<T>(string value)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
Usually it will create a more complex expression of some sort, but if the value is null the method should return a constant, always true expression. In other words:
public static Expression<Func<T, bool>> CreateExpression<T>(string value)
{
if(value == null)
return x => true;
// ...
}
Run Code Online (Sandbox Code Playgroud)
Is this something I can create a …
如何检查表达式树中参数的类型(bool如果类型正确,则获得与 a 等效的表达式树)?如果是普通代码,我会这样做:
if(myObj is int)
Run Code Online (Sandbox Code Playgroud)
我看到有一种Expression.Convert方法,但这会转换对象,而不仅仅是检查其类型。
编辑:我找到了答案,你使用Expression.TypeIs
我正在处理一个小帮手,用于添加,编辑和从数据库中删除对象,add方法现在正在工作,给定一个类型为t的对象,它检查属性,值,并生成一个SQL查询以插入数据到表中(它假设表名是对象的类型,但也可以手动设置)
我现在想做的是一种方法
public bool Update<T>(T obj, Func<T, bool> predicate)
Run Code Online (Sandbox Code Playgroud)
因此给定一个T obj和一个lambda函数谓词,如果谓词是
(o => o.Id = 1)
Run Code Online (Sandbox Code Playgroud)
我想生成
WHERE Id = 1
Run Code Online (Sandbox Code Playgroud)
我已经看到了一些类似的问题,我认为表达式树可能是一个很好的起点,但我所看到的只是如何手动创建表达式,而不是如何从委托创建表达式.
有没有办法从委托生成SQL?
编辑:我终于可以做我想做的事了,我在这里发了一篇关于它的帖子.
我在下面粘贴了我的整个测试应用程序.它相当紧凑,所以我希望这不是问题.您应该能够简单地将其剪切并粘贴到控制台应用程序中并运行它.
我需要能够过滤任何一个或多个Person对象的属性,直到运行时我才知道哪一个.我知道这已经讨论了所有的地方,我已经调查过,并且我也使用了PredicateBuilder和Dynamic Linq Library等工具,但是他们的讨论倾向于更多地关注排序和排序,并且每个人都在努力解决他们的问题.面对Nullable类型时遇到的问题.所以我认为我会尝试至少构建一个可以解决这些特定情况的补充过滤器.
在下面的例子中,我试图过滤掉在某个特定日期之后出生的家庭成员.关键是被过滤对象上的DateOfBirth字段是DateTime属性.
我得到的最新错误是
类型'System.String'和'System.Nullable`1 [System.DateTime]'之间没有定义强制运算符.
这是问题所在.我曾尝试过几种不同的铸造和转换方法,但不同程度的失败.最终,这将适用于EF数据库,该数据库也在转换方法(例如DateTime.Parse( - ))上犹豫不决.
任何帮助都将不胜感激!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Person> people = new List<Person>();
people.Add(new Person { FirstName = "Bob", LastName = "Smith", DateOfBirth = DateTime.Parse("1969/01/21"), Weight=207 });
people.Add(new Person { FirstName = "Lisa", LastName = "Smith", DateOfBirth = DateTime.Parse("1974/05/09") });
people.Add(new Person { FirstName = "Jane", LastName …Run Code Online (Sandbox Code Playgroud) 我有一点问题。我正在尝试将数学表达式添加到二叉树中,但我无法理解该算法。这里是:
If the current token is a '(':
Add a new node as the left child of the current node, and
descend to the left child.
If the current token is in the list ['+','-','/','*']:
Set the root value of the current node to the operator represented by the current token.
Add a new node as the right child of the current node and descend to the right child.
If the current token is a number:
Set the root value …Run Code Online (Sandbox Code Playgroud) 嗨我在c#中创建一个winform应用程序.
我使用EF5来处理数据库.
并且为了将数据绑定到我的datagridviews,我从BindingSource创建了一个组件,该组件具有运行此事件的Bind()方法:
private object bindingSourceTbl1_DataSourceBinding(object sender, EventArgs e)
{
using (SampleDbEntities dbo = new SampleDbEntities())
{
return(from x in dbo.Tbl1
where x.Id == (int)comboBoxPerson.SelectedValue
select x).Take(1000).ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
因为我的数据库有很多大数据,我获取部分数据.我用搜索获得匹配记录.为此,我创建了一个SearchPanel组件,用于创建文本框,用于过滤网格中的每个列.
现在我想将一个表达式树发送到我的事件作为参数加入where子句,如下所示:
private object bindingSourceTbl1_DataSourceBinding(object sender, EventArgs e,Expression whereClause)
{
using (SampleDbEntities dbo = new SampleDbEntities())
{
return(from x in dbo.Tbl1
where x.Id == (int)comboBoxPerson.SelectedValue && whereClause
select x).Take(1000).ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
但我的表达式树构建器方法存在于我的组件代码中,我不能访问我的项目中的DbContext,只是我的组件中有fieldNames,我也想为所有表编写一个方法.
这意味着我无法回归
表达式<Func <AnyDbSet,bool >>
我不知道怎么办?
谢谢
我已经构建了一个表达式树,它从类派生参数并调用它们来设置另一个类中的值.它适用于大多数类型,但在派生类型上失败.如果我有:
public class A
{
public string MyString {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
和
public class B : A
{
}
Run Code Online (Sandbox Code Playgroud)
如果我使用此表达式树代码(其中value是派生实例):
// Get the type of the object for caching and ExpressionTree purposes
var objectType = value.GetType();
// Define input parameter
var inputObject = Expression.Parameter( typeof( object ), "value" );
var properties = objectType.GetProperties( BindingFlags.Instance | BindingFlags.Public );
foreach (var property in properties)
{
Expression.Property( Expression.ConvertChecked( inputObject, property.DeclaringType ), property.GetGetMethod() )
}
Run Code Online (Sandbox Code Playgroud)
我会收到这个例外:
{System.ArgumentException: The method 'My.Namespace.A.get_MyString' is not …Run Code Online (Sandbox Code Playgroud) 我正在尝试转换参数表达式,但无法转换为值类型。以下是我的代码示例:
public static MemberExpression ConvertToType(ParameterExpression sourceParameter,
PropertyInfo propertyInfo,
TypeCode typeCode)
{
var sourceExpressionProperty = Expression.Property(sourceParameter, sourceProperty);
//throws an exception if typeCode is a value type.
Expression convertedSource = Expression.Convert(sourceExpressionProperty,
Type.GetType("System." + typeCode));
return convertedSource;
}
Run Code Online (Sandbox Code Playgroud)
我收到以下无效的操作异常:
No coercion operator is defined between types 'System.String' and 'System.Decimal'.
此转换的任何帮助将不胜感激。
我希望能够使用强类型语法检索类型属性的名称.我已经有一个函数来获取实例的属性名称:
public static string PropertyName<T, TReturn>(this T obj, Expression<Func<T, TReturn>> property) where T : class
{
MemberExpression body = (MemberExpression) property.Body;
if (body == null) throw new ArgumentException("The provided expression did not point to a property.");
return body.Member.Name;
}
Run Code Online (Sandbox Code Playgroud)
可以这样调用:
Car car = new Car();
car.PropertyName(x => x.Wheels) //returns "Wheels"
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建另一个可以支持以下功能:
Type t = Typeof(Car);
t.PropertyName(x => x.Wheels) //should return "Wheels"
Run Code Online (Sandbox Code Playgroud)
或者只是(甚至更好!):
Car.PropertyName(x => x.Wheels)
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
我正在尝试使用名为EvaluateOnCondition的方法创建一个带有Reflection.Emit的类型.我使用Linq表达式生成方法的主体,我想用LambdaExpression的CompileToMethod方法将表达式的IL注入到EvaluateOnCondition中,但是当我执行CompileToMethod方法时,我收到以下错误:
CompileToMethod无法编译常量' 某个值 ',因为它是一个非平凡的值,例如活动对象.而是创建一个可以构造此值的表达式树.
这就是我想要做的:
MethodBuilder evaluateOnCondition = tb.DefineMethod("EvaluateOnCondition", MethodAttributes.Public | MethodAttributes.Static, typeof(bool), new[] { typeof(object), typeof(object) });
onCondition.CompileToMethod(evaluateOnCondition); // throw the error
Run Code Online (Sandbox Code Playgroud)
onCondition变量是LambdaExpression,是使用Linq表达式创建的比较条件,表示以下伪代码:obj1.prop1 == obj2.prop1
这是我的StackTrace:
at System.Linq.Expressions.Compiler.BoundConstants.EmitCacheConstants(LambdaCompiler lc)
at System.Linq.Expressions.Compiler.LambdaCompiler..ctor(AnalyzedTree tree, LambdaExpression lambda, MethodBuilder method)
at System.Linq.Expressions.Compiler.LambdaCompiler.Compile(LambdaExpression lambda, MethodBuilder method, DebugInfoGenerator debugInfoGenerator)
at System.Linq.Expressions.LambdaExpression.CompileToMethodInternal(MethodBuilder method, DebugInfoGenerator debugInfoGenerator)
at System.Linq.Expressions.LambdaExpression.CompileToMethod(MethodBuilder method)
at Integra.Space.Language.Runtime.LanguageTypeBuilder.CreateEqualsMethod(TypeBuilder tb, Type parentType, Type typeOtherSource, Boolean isSecondSource, LambdaExpression onCondition) …Run Code Online (Sandbox Code Playgroud) expression-trees ×10
c# ×8
lambda ×3
linq ×3
reflection ×2
.net ×1
.net-4.5 ×1
c#-4.0 ×1
c++ ×1
cil ×1
expression ×1
typechecking ×1
unit-testing ×1