C# question.
I need to fill my main object property, that is a list of a custom object, but at some point, I need to add to this list a replication with a specific declaration, but I don't want to have to add a line per each item, when there's only and index change on the specific ID of the item in the list.
How to do that with a loop that adds items to a list on the constructor declaration (or so).
Metacode sample:
private static readonly MainObject myObject = new()
{
Type = "OP",
Group = "FD",
Items = new List<SubObject>
{
new SubObject("Tag.Count", 0),
new SubObject("Tag.Min", 0),
new SubObject("Tag.Max", 100),
// Sub list starts here, from 1 to 10
new SubObject("Tag.Pos.1", 1),
new SubObject("Tag.Pos.2", 4),
new SubObject("Tag.Pos.3", 9),
...
new SubObject("Tag.Pos.10", 100),
// Sub list ends here with 10 items
}
}
So, my SubObject list contains what could be solved as a iteration of a single line, but how to do it in this declaration, ... something like, ... were i is a loop item from 1 to 10:
... new SubObject(`Tag.Pos.$i`, $i^2)
Looking for a solution that in the end, returns a sub list that can be added and included in the main list when declaring the object, recognized and accepted by the constructor:
Something that, just line in JavaScript can return something similar to:
...[new SubObject(`Tag.Pos.$i`, $i^2)]
you can try with for loop
private static readonly MainObject myObject = new MainObject
{
Type = "OP",
Group = "FD",
Items = GenerateSubList()
};
private static List<SubObject> GenerateSubList()
{
List<SubObject> subList = new List<SubObject>
{
new SubObject("Tag.Count", 0),
new SubObject("Tag.Min", 0),
new SubObject("Tag.Max", 100)
};
for (int i = 1; i <= 10; i++)
{
subList.Add(new SubObject($"Tag.Pos.{i}", i * i));
}
return subList;
}