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
770 views
in Technique[技术] by (71.8m points)

linq - Parse string to C# lambda Func

Is there a way to convert string representation of lambda to a lambda Func?

Func<Product, bool> func = Parse<Product, bool>("product => product.Name.Length > 0");

I tried Dynamic LINQ but it doesn't work as expected - for example it doesn't expect lambda syntax =>.

Summary of answers:

  • writing my own C# compiler - very funny
  • firing up external compiler (like csc.exe) - very slow
  • using DLINQ - as I said I don't see how it can parse lambda expressions

Why do I need this: because there's no way to pass lambdas to custom attributes like

[Secure(role => role.CanDoThis && role.AllowedCount > 5)]

So as a workaround I'd like to pass lambda as string: "role => role.CanDoThis && role.AllowedCount > 5". But seems like I'll have to use DLINQ like this: "CanDoThis && AllowedCount > 5" - since that's the syntax it understands. But my question was about true lambdas, I've already used DLINQ at the time of asking.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

They are many lambda expression parsers available. Some of them are Lambda-Parser, Sprache

Sample Code:

Example1 : string concat and number calculate:

string code = "2.ToString()+(4*2)"; // C# code Func<string> 
func = ExpressionParser.Compile<Func<string>>(code); // compile code 
string result = func(); // result = "28"

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

...