MattM
MattM

Reputation: 35

How can I create a list of new objects in C#?

I'd like to create a list of objects for a list. I understand it possible to do this below but this isn't what I am after.

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" },
                        }
                    },
                }
            };

Instead of the code above I'd like to create new objects from another list of objects. so something like this;

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

Upvotes: 1

Views: 308

Answers (2)

Demeter Dimitri
Demeter Dimitri

Reputation: 618

You could make a whole new list of the new object type you need to have list of. And for each item in chapterlist, you could create a new list element and add it to the newly made list. So you could serialize or create an object for the each list element.

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);
                    };
              }
         }

Upvotes: -1

Marc Gravell
Marc Gravell

Reputation: 1064104

Well, you could just loop after the initial construction. Doing everything in one statement is over-rated.

However!

new List<Foo>(oldList.Select(x => new Foo { A = x.A, B = x.B, ... }))

should work as a simple clone of the list and list items, as would:

oldList.ConvertAll(x => new Foo { A = x.A, B = x.B, ...})

or (as noted in the comments)

oldList.Select(x => new Foo { A = x.A, B = x.B, ... }).ToList()

Upvotes: 5

Related Questions