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

13,525

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>.

Share:
13,525
LaRae White
Author by

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, 2022

Comments

  • LaRae White
    LaRae White almost 2 years

    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?

  • LaRae White
    LaRae White over 8 years
    Ohhh very good to know. Thought it was part of linq because that's the only time I've really used it, thanks!
  • Lee Song
    Lee Song almost 7 years
    Thanks, I found this after making ForEachWithReturn<T, TResult> extension method.