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
I found this post: Is there an eval function In C#?
And based on the answer posted by rezo-megrelidze:
Works a treat, in the console I can see the correct result.
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):Now it can be used as below. Both examples return 2024: