[英]How can I create a list of new objects in C#?
我想为列表创建对象列表。 我知道可以在下面执行此操作,但这不是我追求的目标。
view.BindingContext =
new ViewModel
{
List = new List<Section> {
new Section
{
Title = "Chapter 1",
List = new List<Reading> {
new Reading { Title = "Title" Text = "abc" },
new Reading { Title = "Title" Text = "abc" },
new Reading { Title = "Title" Text = "abc" },
new Reading { Title = "Title" Text = "abc" },
new Reading { Title = "Title" Text = "abc" },
new Reading { Title = "Title" Text = "abc" },
new Reading { Title = "Title" Text = "abc" },
}
},
}
};
除了上面的代码,我想从另一个对象列表中创建新对象。 像这样
view.BindingContext =
new ViewModel
{
List = new List<Section>
{
foreach(Chapter chapter in ChapterList)
{
new Section { Title = chapter.Title, List = chapter.ReadingList },
}
}
};
好吧,您可以在初始构建后循环。 一句话做所有事情都被高估了。
然而!
new List<Foo>(oldList.Select(x => new Foo { A = x.A, B = x.B, ... }))
应该像列表和列表项的简单克隆一样工作:
oldList.ConvertAll(x => new Foo { A = x.A, B = x.B, ...})
或(如评论中所述)
oldList.Select(x => new Foo { A = x.A, B = x.B, ... }).ToList()
您可以列出需要包含的新对象类型的全新列表。 对于Chapterlist中的每个项目,您可以创建一个新的list元素并将其添加到新创建的列表中。 因此,您可以为每个列表元素序列化或创建一个对象。
new ViewModel
{
Newlist List<differentlist> = new List<differentlist>();
List = new List<Section> {
new Section
{
var ChapterList = new List<ChapterList>();
foreach(var Chapter in ChapterList ){
differentlist new = {Title = String.Empty, List = String.Empty};
new.Title = Chapter.Title;
new.List = Chapter.list;
Newlist.Add(new);
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.