Created
November 16, 2017 16:04
-
-
Save KillerGoldFisch/0d2265072a124b4ee238626e174e7812 to your computer and use it in GitHub Desktop.
Runtime String interpolation for .NET Core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static string Interpolate(string value, System.Collections.Generic.IDictionary<string, object> inject) { | |
| return System.Text.RegularExpressions.Regex.Replace(value, @"{(?<exp>[^}]+)}", match => { | |
| var p = inject.Select(pair => System.Linq.Expressions.Expression.Parameter(pair.Value.GetType(), pair.Key)); | |
| var e = System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda(p.ToArray(), null, match.Groups["exp"].Value, inject.Values.ToArray()); | |
| return (e.Compile().DynamicInvoke(inject.Values.ToArray()) ?? "").ToString(); | |
| }); | |
| } | |
| /* | |
| Dependencys: | |
| * System.Linq.Dynamic.Core | |
| Example: | |
| Console.WriteLine(Interpolate("{x.Name} {y.Value}", new Dictionary<string, object> { | |
| { | |
| "x", new { Name = "Hello" } | |
| }, | |
| { | |
| "y", new { Value = "World" } | |
| } | |
| })); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is perfect and clean solution. Thanks a lot.