Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get linq `ForEach` statement to return data on the method call being made for each list object?

I have a linq ForEach statement that calls a method for each Report object in the list. This method returns an array of data tables for each call and I want to somehow get that returned data. How can I do this using linq ForEach rather than the old school foreach (var x in x's) { ... }? Here is my code:

Reports.ForEach(r => r.LoadTableData(Event, Human, Animal, exData));

How can I get back each DataTable[] that LoadTableData is returning?

like image 290
LaRae White Avatar asked Aug 26 '15 14:08

LaRae White


1 Answers

Use Select instead:

var tables = Reports.Select(r => r.LoadTableData(Event, Human, Animal, exData));

Select maps a collection onto another (in this case, a collection of Report into a collection of DataTable[]). In fact, the Select method is often called map in other languages such as Scala and Ruby.

ForEach executes an arbitrary action for each element in the source collection.

And btw, ForEach is not part of the LINQ extensions. It's just another method on List<T>.

like image 154
dcastro Avatar answered Oct 20 '22 19:10

dcastro