Last active
December 15, 2015 03:28
-
-
Save akimboyko/5193989 to your computer and use it in GitHub Desktop.
Roslyn and anonumous types within script
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
void Main() | |
{ | |
var engine = new ScriptEngine(); | |
new[] | |
{ | |
typeof (Math).Assembly, | |
this.GetType().Assembly | |
}.ToList().ForEach(assembly => engine.AddReference(assembly)); | |
new[] | |
{ | |
"System", "System.Math", | |
typeof(Model.ProcessingModel).Namespace | |
} .ToList().ForEach(@namespace => engine.ImportNamespace(@namespace)); | |
IEnumerable<Model.ProcessingModel> models = new[] | |
{ | |
new Model.ProcessingModel { InputA = 10M, InputB = 5M, Factor = 0.050M }, | |
new Model.ProcessingModel { InputA = 20M, InputB = 2M, Factor = 0.020M }, | |
new Model.ProcessingModel { InputA = 12M, InputB = 3M, Factor = 0.075M }, | |
new Model.ProcessingModel { InputA = 0M, InputB = 9M, Factor = 0.800M }, | |
}; | |
// no dynamic allowed | |
// no async/await allowed | |
var script = | |
@" | |
Result = InputA + InputB * Factor; | |
Delta = Math.Abs((Result ?? 0M) - InputA); | |
Description = ""Some description""; | |
new { Σ = Result, Δ = Delta, λ = Description } | |
"; | |
var submissionModel = new Model.ProcessingModel(); | |
var session = engine.CreateSession(submissionModel); | |
var submission = session.CompileSubmission<dynamic>(script); | |
IEnumerable<dynamic> results = | |
models.Select(model => | |
{ | |
submissionModel.InjectFrom(model); | |
return submission.Execute(); | |
}); | |
results | |
.Zip(models, (result, model) => new { result, model }) | |
.Select(@group => | |
new | |
{ | |
@return = @group.result, | |
ResultModel = @group.model | |
}).Dump(); | |
} | |
} | |
namespace Model | |
{ | |
public class ProcessingModel | |
{ | |
public decimal InputA { get; set; } | |
public decimal InputB { get; set; } | |
public decimal Factor { get; set; } | |
public decimal? Result { get; set; } | |
public decimal? Delta { get; set; } | |
public string Description { get; set; } | |
public decimal? Addition { get; set; } | |
} | |
public class ReportModel | |
{ | |
public decimal? Σ { get; set; } | |
public decimal? Δ { get; set; } | |
public string λ { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
StackOverflow discussion