"new" 运算符中的 For 循环
For-loop within "new"-operator
我正在寻找一种方法来以交互方式创建具有灵活数量元素的列表对象。目前,我有固定数量的元素;我可以这样创建对象:
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 },
};
有没有办法直接构造这样一个元素个数任意的对象? (在 new() 中编写循环的微不足道的尝试 - 不出所料,构造确实不起作用)
为此目的使用 linq 和 Enumerable:
Enumerable.Range(1, 12) // 12 cand be other number
.Select(x =>
new DropItem
{
Name = "Cam " + x,
cam_idx = x
... // whatever you want
}).ToList();
Enumerable.Range()
应该能帮到你
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();
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});
}
我正在寻找一种方法来以交互方式创建具有灵活数量元素的列表对象。目前,我有固定数量的元素;我可以这样创建对象:
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 },
};
有没有办法直接构造这样一个元素个数任意的对象? (在 new() 中编写循环的微不足道的尝试 - 不出所料,构造确实不起作用)
为此目的使用 linq 和 Enumerable:
Enumerable.Range(1, 12) // 12 cand be other number
.Select(x =>
new DropItem
{
Name = "Cam " + x,
cam_idx = x
... // whatever you want
}).ToList();
Enumerable.Range()
应该能帮到你
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();
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});
}