相关疑难解决方法(0)

如何撰写现有的Linq表达式

我想编写两个Linq表达式的结果.它们以形式存在

Expression<Func<T, bool>>
Run Code Online (Sandbox Code Playgroud)

所以我要编写的两个本质上是一个参数(类型为T)的委托,它们都返回一个布尔值.我想要的结果是对布尔值的逻辑评价.我可能会将它作为扩展方法实现,所以我的语法将是这样的:

Expression<Func<User, bool>> expression1 = t => t.Name == "steve";
Expression<Func<User, bool>> expression2 = t => t.Age == 28;
Expression<Func<User, bool>> composedExpression = expression1.And(expression2);
Run Code Online (Sandbox Code Playgroud)

后来在我的代码中我想评估组合表达式

var user = new User();
bool evaluated = composedExpression.Compile().Invoke(user);
Run Code Online (Sandbox Code Playgroud)

我用了一些不同的想法,但我担心它比我希望的更复杂.这是怎么做到的?

c# linq

11
推荐指数
1
解决办法
9338
查看次数

将Linq表达式"obj => obj.Prop"转换为"parent => parent.obj.Prop"

我有一个类型的现有表达Expression<Func<T, object>>; 它包含像cust => cust.Name.

我还有一个带有类型字段的父类T.我需要一个接受上面作为参数的方法,并生成一个新的表达式,将父类(TModel)作为参数.这将用作MVC方法的表达式参数.

因此,cust => cust.Name成为parent => parent.Customer.Name.

同样,cust => cust.Address.State成为parent => parent.Customer.Address.State.

这是我的初始版本:

    //note: the FieldDefinition object contains the first expression
    //described above, plus the MemberInfo object for the property/field
    //in question
    public Expression<Func<TModel, object>> ExpressionFromField<TModel>(FieldDefinition<T> field)
        where TModel: BaseModel<T>
    {
        var param = Expression.Parameter(typeof(TModel), "t");

        //Note in the next line "nameof(SelectedItem)". This is a reference
        //to the property in …
Run Code Online (Sandbox Code Playgroud)

c# linq asp.net-mvc linq-expressions

8
推荐指数
1
解决办法
572
查看次数

标签 统计

c# ×2

linq ×2

asp.net-mvc ×1

linq-expressions ×1