在C#中,对象初始化期间,开发人员无需使用特定的构造函数签名即可指定属性值,并且我想知道是否有可能使用一个动态的条目数来填充数组属性。 foreach循环(或其他一些动态循环方法)。
例如...
public class MyObject
{
public string[] ArrayOfItems { get; set; }
public MyObject()
{
}
}
public class Item
{
public string ItemName { get; set; }
public Item()
{
}
}
public void CreateNewMyObject()
{
//List would normally come from elsewhere...
List<Item> ItemList = new List<Item>()
{
new Item() { ItemName = "Item One" },
new Item() { ItemName = "Item Two" },
new Item() { ItemName = "Item Three" }
};
MyObject myObject = new MyObject()
{
ArrayOfItems = new string[]
{
// This is where I'm stuck.
// I want to dynamically build my array but cant use foreach?
foreach (Item item in ItemList)
{
item.ItemName
}
};
}
}
答案 0 :(得分:2)
像这样使用LINQ:
MyObject myObject = new MyObject()
{
ArrayOfItems = ItemList.Select(i => i.ItemName).ToArray()
}
如果ArrayOfItems
是复杂类型,例如MyArrayItem
和Item
拥有额外的ItemCost
属性,您可以这样做:
MyObject myObject = new MyObject()
{
ArrayOfItems = ItemList.Select(i => new MyArrayItem() { Name = i.ItemName, Cost = i.ItemCost }).ToArray()
}
MyArrayItem
应该具有匹配的构造函数:
MyObject myObject = new MyObject()
{
ArrayOfItems = ItemList.Select(i => new MyArrayItem(i.ItemName, i.ItemCost)).ToArray()
}