Expression.Call usage

c# expression-trees

Question

I have tried to convert the string to ToLower case using the below Expression call.

var tolowerMethod = typeof(string).GetMethods().Where(m => m.Name == "ToString").FirstOrDefault(); 
var toLowerMethodCall = Expression.Call(memExp,tolowerMethod,new Expression[0]);

I am facing some issue to create an Expression call to format a value like: "05/12/2012 12:00:00" to {0:MM/dd/yyyy}.

Popular Answer

Well there's no such method that can take a date string in one format and reformat it to another. You'd have to convert that string to a DateTime then back to a string.

Here's how you could create such a lambda:

var dateStr = Expression.Parameter(typeof(string));
var asDateTime = Expression.Call(typeof(DateTime), "Parse", null, dateStr); // calls static method "DateTime.Parse"
var fmtExpr = Expression.Constant("MM/dd/yyyy");
var body = Expression.Call(asDateTime, "ToString", null, fmtExpr); // calls instance method "DateTime.ToString(string)"
var lambdaExpr = Expression.Lambda<Func<string, string>>(body, dateStr);

Then compile and call it.

var method = lambdaExpr.Compile();
method("05/12/2012 12:00:00"); // "05/12/2012"


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why