如何在C#中创建新对象列表?

Mat*_*ttM 1 c# list object

我想为列表创建一个对象列表.我知道可以在下面这样做,但这不是我所追求的.

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" },
                        }
                    },
                }
            };
Run Code Online (Sandbox Code Playgroud)

而不是上面的代码我想从另一个对象列表创建新对象.所以这样的事情;

view.BindingContext =
            new ViewModel
            {
                List = new List<Section>
                {
                 foreach(Chapter chapter in ChapterList)
                    {
                    new Section { Title = chapter.Title, List = chapter.ReadingList },
                    }
                }
            };
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

好吧,你可以在初步建设循环.在一个陈述中做所有事情都被高估了.

然而!

new List<Foo>(oldList.Select(x => new Foo { A = x.A, B = x.B, ... }))
Run Code Online (Sandbox Code Playgroud)

应该作为列表和列表项的简单克隆,如下所示:

oldList.ConvertAll(x => new Foo { A = x.A, B = x.B, ...})
Run Code Online (Sandbox Code Playgroud)

或(如评论中所述)

oldList.Select(x => new Foo { A = x.A, B = x.B, ... }).ToList()
Run Code Online (Sandbox Code Playgroud)