Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Advice - Using ToList().ForEach instead of 'classic' ForEach iteration

Tags:

c#

linq

I would like to use LINQ's ForEach construct and am not sure how to convert the following.

My current implementation:

var employees = (from e in employeeDepartmentList select e.Employee).ToList();
employeeList = new EmployeeList();
foreach (var emp in employees)
{
   employeeList.Add(emp);
}

I am thinking something like this:

employeeList = new EmployeeList();
var employees = (from e in employeeDepartmentList select e.Employee).ToList().ForEach(emp => employeeList.Add(emp));
like image 323
user118190 Avatar asked Aug 27 '10 15:08

user118190


1 Answers

ForEach is not a LINQ method, it is a method of List<>. In this simple scenario, why even use that? employeeList.AddRange(employees) would be even simpler. Even further, if employees is already a list, do you need employeeList?

As for more advice on using foreach vs. ForEach in general, see: http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx

like image 104
Anthony Pegram Avatar answered Oct 05 '22 22:10

Anthony Pegram