Copy one List to another List and SubList with LINQ

c#, c#-4.0, linq, linq-to-objects

Solution

It will be better to iterate through the input parameter employeeValuesCollection list inside the Employee constructor to create a local variable of type EmployeeValues and add it to the Employee class's instance list variable. If we use EmployeeValuesCollection = employeeValuesCollection;, we are actually assigning the reference. So if we modify some values of employeeValuesCollection, the same change will get reflected to EmployeeValuesCollection.

public Employee(int employeeID, string jobTitle, int companyID, List<EmployeeValues> employeeValuesCollection)
    {
        EmployeeID = employeeID;
        JobTitle = jobTitle;
        CompanyID = companyID;

        foreach (var obj in employeeValuesCollection)
        {
            var empVal = new EmployeeValues() { Name = obj.Name};
            EmployeeValuesCollection.Add(empVal);
        }

And you can use the LINQ statement as

dataFiles.ForEach(l => employeeList.Add(new Employee(l.EmpID, l.JobTitle, l.CompID, l.EmployeeValuesCollection)));

Problem

I have a list of employees, and all of them have another list nested which is called the EmployeeValuesCollection. So my class is something like :- ``` public Employee(int employeeID, string jobTitle, int companyID, List<EmployeeValues> employeeValuesCollection) { EmployeeID = employeeID; JobTitle = jobTitle; CompanyID = companyID; EmployeeValuesCollection = employeeValuesCollection; } ``` Now I wish to populate this object from another object with LINQ, and so far I have :- ``` List<DataFileRow> dataFiles = dfRow.Rows; dataFiles .ForEach(l => employeeList .Add(new Employee(l.EmpID, l.JobTitle, l.CompID))); ``` That works however I do not know how to add the employeeValuesCollection in the statement. Is it possible to do? So I was thinking something like :- ``` dataFiles .ForEach(l => employeeList .Add(new Employee(l.EmpID, l.JobTitle, l.CompID, new List<EmployeeValuesCollection> .............))); ``` Thanks for your help and time.

Original source