How to add items into the list from other list using for each C# smart technique

Viewed 78

Can I add list data from other list items using for each loop without extracting the method? I want to add a new list to PersDriver.

Here is the code where PersDriver is a list of Test class and AutoDrivers is a list passing from the model. But I am getting an error at the end of the new PersDriver() {} that ; expected. Can anyone correct my simple code without extracting a new method or add it to the list?

Test t1 = new Test(testModel model)
{
   PersDriver = new List<PersDriver>() 
   {
       model.AutoDrivers.ForEach(_driver =>
       {
           new PersDriver()
           {
               Id= _driver.Id,
               Name = _driver.Name
           }
       }
   }
}
1 Answers

You can try LINQ:

Test t1 = new Test(testModel model)
{
   PersDriver = model.AutoDrivers.Select(_driver =>
      new PersDriver()
      {
           Id= _driver.Id,
           Name = _driver.Name
      }).ToList()
};
Related