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
}
}
}
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can try LINQ:
Test t1 = new Test(testModel model)
{
PersDriver = model.AutoDrivers.Select(_driver =>
new PersDriver()
{
Id= _driver.Id,
Name = _driver.Name
}).ToList()
};
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0