Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Last active December 14, 2015 16:29
Show Gist options
  • Save akimboyko/5115064 to your computer and use it in GitHub Desktop.
Save akimboyko/5115064 to your computer and use it in GitHub Desktop.
Processing IEnumerable with Roslyn script. Sample for LinqPAD
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
// anonymous class are duplicated in assembly
var script =
@"
Result = InputA + InputB * Factor;
Delta = Math.Abs((Result ?? 0M) - InputA);
Description = ""Some description"";
new ReportModel{ Σ = Result, Δ = Delta, λ = Description }
//new { Σ = Result, Δ = Delta, λ = Description }
";
// at least `dynamic` is more flexible than `object`, but statis typing even better
//IEnumerable<dynamic> results = models
IEnumerable<Model.ReportModel> results = models
.Select(model => engine.CreateSession(model).Execute(script))
.Cast<Model.ReportModel>();
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;
public decimal InputB;
public decimal Factor;
public decimal? Result;
public decimal? Delta;
public string Description;
public decimal? Addition;
}
public class ReportModel
{
public decimal? Σ;
public decimal? Δ;
public string λ;
}
@akimboyko
Copy link
Author

Current Roslyn CTP has following limitations:

  • no dynamic allowed
  • no async/await allowed
  • exception "anonymous class are duplicated in assembly"

@akimboyko
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment