如何获得谓词T在运行时从字符串表达式 [英] How to get Predicate<T> from string expressions at runtime

查看:108
本文介绍了如何获得谓词T在运行时从字符串表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用EntityFramework的Winform应用程序中,我使用BaseForm的BindingSource实现通用的Search/Filter UI组件,并根据用户输入和BindingSource(上下文实体)的DataSource属性动态构建搜索/过滤器字符串表达式.

In Winform application using EntityFramework, I implement a generic Search / Filter UI Components using BindingSource of the BaseForm and build search/filter string expression dynamically from user inputs and properties of the DataSource of BindingSource (Context entity).

查找和过滤器, 因为ObjectContext或DataContext的查询结果是IEnumerable类型,所以没有实现IBindingList接口

Find and Filter aren't supported by the BindingSource in EntityFramework, because the query result of ObjectContext or DataContext was IEnumerable type, which didn't implement IBindingList interface ref

作为解决方法,我将BindingSource强制转换为List<T>.

As a workaround I Cast BindingSource to List<T>.

要实现一个,我使用List<T>.Find(predicate)并且谓词是lambda表达式.

To implement one, I use List<T>.Find(predicate) and the predicate is a lambda Expression.

要将谓词传递给List<T>.Find(predicate),我需要将动态生成的字符串表达式转换为Predicate.

To Pass a Predicate to List<T>.Find(predicate), I need To convert the dynamic generated string expression to Predicate .

字符串表达式示例:

"CategoryId = 5且价格<10"

"CategoryId = 5 and Price < 10"

使用类似方法进行操作

Predicate<T>  GetPredicate <T>(string expression)
{   
    //how  to convert the string expressions to    Predicate<T> 
}

然后将谓词传递给方法List<T>. Find(predicat)

Then pass the predicate to the method List<T>. Find(predicat)

我可以使用.Where (dynamicStringExpression),但是对于我的组件,我需要GetPredicate(dynamicStringExpression)

I can use .Where (dynamicStringExpression), but for my component I need GetPredicate(dynamicStringExpression)

如何从字符串表达式获取Predicate<T>

How to get Predicate<T> from string expressions

推荐答案

我使用了 System.Linq.Dynamic 基于 MicroSoft的先前工作

Install-Package System.Linq.Dynamic

Install-Package System.Linq.Dynamic

我实现了以下静态/Extension方法:

I Implemented the following static /Extension methods:

using System;
using System.Collections.Generic;
using DynamicExpression=System.Linq.Dynamic.DynamicExpression; //nuget package
using System.Linq.Expressions;

public static class MyDynamics
{           
    public static Predicate<T> GetPredicate<T>(string stringExpression)
    {        
        var exp = DynamicExpression.ParseLambda<T, bool>(stringExpression).Compile();               
        var predicate = new Predicate<T>(exp);
        return predicate;
    }   
}

使用方法:

Console.WriteLine("------- Find items using string expression ------");     
//use string expression
var predicate = MyDynamics.GetPredicate<Part>("PartId==1444");
//pass  the predicate to List.Find
var part= parts.Find(predicate);
Console.WriteLine("Part: Find: PartId= {0} , PartName={1}",part.PartId, part.PartName);

小提琴

这篇关于如何获得谓词T在运行时从字符串表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆