Is it possible to convert a foreach operation to LINQ if it has two functions?

I have a working foreach as follows.

List<Thing> things = new List<Thing>();
foreach (Original original in originals)
  things.Add(new Thing(orignal));

Then I got smart and LINKified in the following code still working .

IEnumerable<Thing> things = originals.Select(origo => new Thing(origo));

Feeling really proud of the reduction in the number of lines, as well as LINQing for clearer code, I realized that there is also a requirement to update the process table. It is necessary that the update happen simultaneously when we go through the transformation. So, with my tail between my legs and a feeling of much less pride, I went back to the source code and added a notification method.

List<Thing> things = new List<Thing>();
foreach (Original original in originals)
{
  things.Add(new Thing(orignal));
  DoTell();
}

, LINQie - - . , (, , ). - , .

+4
5

. .

IEnumerable<Thing> things = originals.Select(origo => {DoTell(); return new Thing(origo)});

new Thing Select. , , new Thing DoTell()

foreach, . LINQ / .

EDIT:

LINQ, ():

var things = things.Select(x => new { o = new Thing(), b = DoTell()}).Select(x=>x.o);

. :)

+5

, Select

IEnumerable<Thing> things = originals.Select(origo => 
                                                    {
                                                       DoTell();
                                                       return new Thing(origo);
                                                     });

, DoTell() , new Thing, , :

IEnumerable<Thing> things = originals.Select(origo => 
                                                        {
                                                           var thing = new Thing(origo);
                                                           DoTell();
                                                           return thing;
                                                         });
+2
originals.ToList().ForEach(x=>{things.Add(new Thing(x));DoTell();});
+1
originals.ForEach(q =>
{
   //do first thing
   //do second thing 
});
+1

Additional explanation The return type forEach is void, however Select has a return type of IEnumerable. Therefore, the use of both depends on the context.

0
source

Source: https://habr.com/ru/post/1612356/


All Articles