David
David

Reputation: 218887

Iterating a List in an Object Initializer

When building an object with the object initializer syntax, is there a way to iterate over a list in one of the assignment statements and assign an output of the iteration to that property?

For example, I have a Person model which I'm converting into a Person view model (mostly because the Person model has lazy-loaded properties and is highly and potentially recursively dynamic, but the view is disconnected over the web and just needs a single Person instance to be serialized). I'm also using the nVentive Umbrella extensions for handy things like .ForEach() on enumerables. So to output my list of Person view models from my Person models, I convert them like this:

people.ForEach(p =>
  returnPeople.Add(
    new Person{
      FirstName = p.FirstName,
      ID = p.ID,
      LastName = p.LastName,
      MiddleName = p.MiddleName,
      NamePrefix = p.NamePrefix,
      NameSuffix = p.NameSuffix,
      ParentsID = p.Parents == null ? 0 : p.Parents.ID,
      PartnershipIDs = new List<int>(),
      Sex = p.Sex.ToString()
    }
  )
);

I'm iterating over the collection of Person models (people) and populating the collection of Person view models (returnPeople). Everything works fine, but I also want to populate that PartnershipIDs property in the same statement. Functionality such as:

//....
PartnershipIDs = p.Partnerships.ForEach(par => yield return par.ID)
//....

That, however, doesn't work. The compiler doesn't like the syntax. But is there a way to accomplish that functionality in this setup? Or do I have to initialize the Person view model with all but one field first, and then on the next line populate the remaining field?

Upvotes: 2

Views: 3232

Answers (2)

Matthew Abbott
Matthew Abbott

Reputation: 61599

Perhaps instead of doing a ForEach, you do a Select:

PartnershipIDs = p.Partnerships.Select(par => par.ID).ToList();

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160922

You need a simple projection:

PartnershipIDs = p.Partnerships.Select(par => par.ID).ToList()

Upvotes: 5

Related Questions