Search code examples
c#lambda

How to apply modifier to expression


I have an XML file, here is a snippet:

<response>
  <data offset="4" length="2" pattern="[%lx]" desc="Hours"/>
  <data offset="2" length="2" pattern="[%lx]" desc="Minutes"/>
  <data offset="0" length="2" pattern="[%lx]" desc="Seconds"/>
  <data offset="6" length="2" pattern="[%lx]" desc="Day"/>
  <data offset="8" length="2" pattern="[%lx]" desc="Month"/>
  <data offset="10" length="2" pattern="[%lx]" desc="Year" modifier="+2020"/>
</response>

This is used to decode a response in code which is the time and date, the year is returned in the response as 04, I want to apply the modifier to this value, I'm trying to keep it as flexible and generic as possible.

How can I take the value of the modifier which I have in code as a string and apply it to the value? My code:

double dblData = 0.0;
if (double.TryParse(strData, out dblData) == true) {
...
}

strData is a string which in this case contains 04, how can I apply the modifier which I have in another variable called strModifier to strData so it becomes 04+2020 and the result is 2024?

Can I do this with Lambda?

I am using Microsoft Visual Studio Professional 2022, version 17.11.3, the project is using the Target framework .NET Framework 4.8, Output type Windows Application.

I am having problems trying out the suggestions because I cannot add Microsoft.CodeAnalysis.CSharp.Scripting, I've also tried the other suggested answer but the code will not compile.


Solution

  • I found this post: Is there an eval function In C#?

    And based on the answer posted by rezo-megrelidze:

    if (cdmProvider == null) {
        cdmProvider = new CSharpCodeProvider();
    }
    if (cdmProvider != null) {
        string strModifier = detail.strModifier;
        strModifier = strModifier.Replace(mcstrValue, strData);
        CompilerResults results = cdmProvider.CompileAssemblyFromSource(
            new CompilerParameters()
          , new string[] {                                                                    
            string.Format(@"namespace nsILC {{
                public class clsILC {{
                    public double Eval() {{
                        return {0};
                    }}
                }}", strModifier)
            });
    Assembly test = results.CompiledAssembly;
    dynamic evalulator = Activator.CreateInstance(test.GetType("nsILC.clsILC"));
    Console.WriteLine(evalulator.Eval());                                                    
    

    Works a treat, in the console I can see the correct result.