Tutorial :Multiple Selection in ForEach Extension Method



Question:

Is it possible to select multiple entiies in ForEach Extension Method?

(i.e)

partial code is given

DataTableA.AsEnumerable().ToList().      ForEach(x=>      {          x.SetField<string>("Name","Jon Skeet"),          x.SetField<string>("msg","welcome")      });  

when i apply multiple selection in ForEach

 x=>  {      x.SetField<string>("Name","Jon Skeet"),      x.SetField<string>("msg","welcome")  }  

I am unable to complete the statement.Help Please.


Solution:1

You need to make the lambda compile to valid C#:

DataTableA.AsEnumerable().ToList().ForEach(       x=>         {           x.SetField<string>("Name","Jon Skeet");           x.SetField<string>("msg","welcome");        });  

That being said, I'd caution against this. Using ForEach is purposely causing side-effects, and it's really not more concise than the foreach statement in the language itself. Personally, I'd just write:

foreach(var element in DataTableA.AsEnumerable())  {      element.SetField<string>("Name","Jon Skeet");      element.SetField<string>("msg","welcome");  }  

This, in my opinion, is much more clear than the first statement (and shorter, and more efficient, since it doesn't force a full enumeration into the list, and a second enumeration of the list elements).


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »