Home > Blockchain >  For-loop within "new"-operator
For-loop within "new"-operator

Time:03-17

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)

CodePudding user response:

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

CodePudding user response:

Use linq and Enumerable for this purpose:

Enumerable.Range(1, 12) // 12 cand be other number
.Select(x =>
new DropItem
{
    Name = "Cam "   x,
    cam_idx  = x
    ... // whatever you want 
}).ToList();

CodePudding user response:

int itemsCount = 8;
for (int i = 0; i < itemsCount; i  )
{
    _items.Add(new DropItem() { Name = $"Cam {i}", Identifier = $"Drop Zone {i / 4   1}", cam_idx = i});
}
  • Related