有没有一种方法可以初始化一个包含现有项目的类中的列表?实例化一个类对象并初始化一个列表
我基本上想要实例化一个类对象,并从现有和新项目中初始化一个已经存在的元素的列表。
public class Item
{
public string Property {get; set;}
}
public class MyClass
{
public virtual IEnumerable<Item> Items {get; set;}
}
var itemToAdd = context.Items(i => i.Property == "Desired");
MyClass myclass = new MyClass()
{
Items = new List<Item>()
{
new List<Item>(),
{
Property = "New"
},
// Would like itemToAdd to be added here when I create a new List.
}
};
如果我只想传递一个项目,语法会是什么? – khaihon 2012-04-27 00:12:07
然后你可能不会使用构造函数。在初始化之后,您将它留空并进行Items.Add(itemToAdd)调用。然而代码“context.Items(i => i.Property ==”Desired“);”即使只有一个项目,也会返回一个集合。 – nmaait 2012-04-27 00:21:54