Ad

For-loop Within "new"-operator

- 1 answer

I am looking for a way to interactively create a List-Object with a flexible number of elements. At the moment, i have a fixed number of elements; i can create the Object like this:

private List<DropItem> _items = new()
{


new DropItem(){ Name = "Cam 0", Identifier = "Drop Zone 1", cam_idx = 0 },
new DropItem(){ Name = "Cam 1", Identifier = "Drop Zone 1", cam_idx = 1 },
new DropItem(){ Name = "Cam 2", Identifier = "Drop Zone 1", cam_idx = 2 },
new DropItem(){ Name = "Cam 3", Identifier = "Drop Zone 1", cam_idx = 3 },
new DropItem(){ Name = "Cam 4", Identifier = "Drop Zone 2", cam_idx = 4 },
new DropItem(){ Name = "Cam 5", Identifier = "Drop Zone 2", cam_idx = 5 },
new DropItem(){ Name = "Cam 6", Identifier = "Drop Zone 2", cam_idx = 6 },
new DropItem(){ Name = "Cam 7", Identifier = "Drop Zone 2", cam_idx = 7 },
};

Is there a way to directly construct such an object with an abitrary number of elements? (a trivial attempt to write a loop within the new() - construction did unsurprisingly not work)

Ad

Answer

Enumerable.Range() should help you here

int count = 10;
List<DropItem> _items = Enumerable.Range(0, count).Select(x => new DropItem()
{
    Name = "Cam " + x,
    Identifier = "Drop Zone" + ((x < count / 2) ? 1 : 2),
    cam_idx = x
}).ToList();

https://dotnetfiddle.net/ePpi5T

Ad
source: stackoverflow.com
Ad