Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For-loop within "new"-operator

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading