skip to Main Content

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.

3

Answers


  1. Chosen as BEST ANSWER

    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.


  2. using Microsoft.CodeAnalysis.CSharp.Scripting;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            string strData = "04";
            string strModifier = "+2020";
    
            int result = (int) await CSharpScript.EvaluateAsync(strData + strModifier);
        } 
    }
    
    Login or Signup to reply.
  3. You could try this code. As I saw, the value of modifier could be also +,2020, so here’s generic approach to account also for that (explanations in code):

    static double Parse(string strData, string modifier)
    {
        // Parse strData to number
        var @double = double.Parse(strData);
        // Extract operation to perform from first character.
        var operation = modifier[0];
        // Apply regex to capture all numbers:
        // it just captures consecutive digits
        // and parses to number.
        var numbers = Regex.Matches(modifier.Substring(1), @"d+")
            .Select(x => double.Parse(x.Value))
            .ToArray();
        // Apply operation based on extracted information.
        // Also, if you are sure there will be always one number,
        // you can use numbers[0] instead of numbers.Sum()
        return operation switch
        {
            '+' =>  @double + numbers.Sum(),
            //'-' =>  @double - numbers.Sum(),
            //'*' =>  @double * numbers.Sum(),
            _ => throw new NotSupportedException(),
        };
    }
    

    Now it can be used as below. Both examples return 2024:

    var result1 = Parse("04", "+2020");
    var result2 = Parse("04", "+,2020");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search