Dynamic string interpolation

Jitendra Tiwari picture Jitendra Tiwari · Oct 5, 2016 · Viewed 13.6k times · Source

Can anyone help me with this?

Required Output: "Todo job for admin"

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(ReplaceMacro("{job.Name} job for admin", new Job { Id = 1, Name = "Todo", Description="Nothing" }));
        Console.ReadLine();
    }

    static string ReplaceMacro(string value, Job job)
    {
        return value; //Output should be "Todo job for admin"
    }
}

class Job
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

Answer

Dan picture Dan · Oct 6, 2016

Two suggestions:

DataBinder.Eval

string ReplaceMacro(string value, Job job)
{
    return Regex.Replace(value, @"{(?<exp>[^}]+)}", match => {
        return (System.Web.UI.DataBinder.Eval(new { Job = job }, match.Groups["exp"].Value) ?? "").ToString();
    });
}

Linq.Expression

Use the Dynamic Query class provided in the MSDN LINQSamples:

string ReplaceMacro(string value, Job job)
{
    return Regex.Replace(value, @"{(?<exp>[^}]+)}", match => {
        var p = Expression.Parameter(typeof(Job), "job");
        var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p }, null, match.Groups["exp"].Value);
        return (e.Compile().DynamicInvoke(job) ?? "").ToString();
    });
}

In my opinion, the Linq.Expression is more powerful, so if you trust the input string, you can do more interesting things, i.e.:

value = "{job.Name.ToUpper()} job for admin"
return = "TODO job for admin"