Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

c# - How to get Predicate<T> from string expressions at runtime

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).

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

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

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

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

String Expression example:

"CategoryId = 5 and Price < 10"

To Something using a method like:

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

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

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

How to get Predicate<T> from string expressions

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As suggested in the comments its better to use Dynamic Linq. As find() is the equivalent of Where().FirstOrdefault():

List<T>.AsQueryable().Where("CategoryId = 5 and Price < 10").FirstOrDefault();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...