How to get linq `ForEach` statement to return data on the method call being made for each list object?
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>
.
LaRae White
Software Engineer, Database Engineer, Graphics Programmer, Newbie C#/.NET, T-SQL, C++, JavaScript, VB, XML,JSON, HTML5, CSS3, SpecFlow/Gherkin/Cucumber I love lamp
Updated on June 05, 2022Comments
-
LaRae White almost 2 years
I have a linq
ForEach
statement that calls a method for eachReport
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 schoolforeach (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[]
thatLoadTableData
is returning? -
LaRae White over 8 yearsOhhh very good to know. Thought it was part of linq because that's the only time I've really used it, thanks!
-
Lee Song almost 7 yearsThanks, I found this after making ForEachWithReturn<T, TResult> extension method.