0

I want to do something like this:

for (var i =0; i < obj.ValueList.Count; i++)
{
  var runCode = $"oldObj.Mod{i+1} = obj.ValueList[{i}].Value;";
  // Execute runCode; then 'oldObj.Mod1 = obj.ValueList[0].Value'
}

... I just think it will ultimately be better than 5 or 10 or 100 explicit repetitions of oldObj.Mod1 = obj.ValueList[0].Value.

It has to have been done before.

Thoughts? Help? Direction?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

2 Answers2

1

Disclaimer: I'm the owner of C# Eval Expression

This library allows executing dynamic C# code at runtime. It's not free but also to easily solve this kind of problem.

Online example: https://dotnetfiddle.net/B5t9jD

var oldObj = new OldObj();

var obj = new Obj() { ValueList = new List<ObjValue>() { new ObjValue(111), new ObjValue(222), new ObjValue(333), new ObjValue(444), new ObjValue(555) }};

for (var i = 0; i < obj.ValueList.Count; i++)
{
  var runCode = Eval.Execute("oldObj.Mod" + (i+1) + " = obj.ValueList["+i+"].Value;", new { oldObj, obj});
}

FiddleHelper.Dump(oldObj);
Jonathan Magnan
  • 10,874
  • 2
  • 38
  • 60
0

I can't be sure if you really have to use for loop, but you can actually try to get the properties with reflection and then set values (see: https://stackoverflow.com/a/30475988/9709828) or you can also try to play with LINQ for getting necessarily list of oldObj's properties and set values through the for loop

yemo
  • 145
  • 8