tags:

views:

102

answers:

2

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));
+3  A: 

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

Anthony Pegram
Thanks Anthony for your reply - employees is already a list, but if you notice, it is getting data from a List of type <EmployeeDepartments>. I would like to search this list of EmployeeDepartments and basically get the Employee properties out and "cast" it into a List<Employee>. Am I doing this totally wrong?
If e.Employee is of type `Employee`, then `employees` will be a `List<Employee>`. I see that `employeeList` is a different type (`EmployeeList()`), so I cannot speak to say that `AddRange` is available to it (it is a member of `List<>`, and I don't know if `EmployeeList` inherits from this or not).
Anthony Pegram
Thaks Anthony - I just looked at the link you sent me and that solution worked for me.foreach(Foo foo in foos){ statement involving foo; }into this code:foos.ForEach((Foo foo)=>{ statement involving foo; });
A: 

Here is the option we decided to go with. We added a class to house extension methods. By placing this in a common assembly, we can use it throughout the enterprise

   public static class IEnumerableExtensions
   {
      public static void ForEach<T>( this IEnumerable<T> source, Action<T> action )
      {
         foreach ( T item in source )
            action( item );
      }
   }
DevSolo
What do you get out of using this instead of a foreach loop? This will be slightly less performant, without any benefit. And it's also a little unexpected for a Linq function to not be lazily evaluated. As my colleague said when he saw something like this: "Linq is a query language, not a do-ey language."
John Gibb
P.S. The intent of the List<T>.ForEach method is performance. It skips the whole .GetEnumerator() and .MoveNext() code. However, you're getting the lousy syntax without the performance benefit here.
John Gibb