Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach to linq tip wanted

Tags:

c#

linq

How do I do this in linq?

var p = new pmaker();

 foreach (var item in itemlist)
 {
   var dlist = new List<Dummy>();
   foreach (var example in item.examples)
   { 
     dlist.Add(example.GetDummy()); 
   }
   p.AddStuff(item.X,item.Y,dlist);
 }

// .. do stuff with p
like image 269
Nifle Avatar asked Feb 02 '26 23:02

Nifle


1 Answers

How about:

var qry = from item in itemlist
          select new {item.X, item.Y,
              Dummies = item.examples.Select(
                ex => ex.GetDummy())
          };
foreach (var item in qry)
{
    p.AddStuff(item.X, item.Y, item.Dummies.ToList());
}

Not sure it is much clearer like this, though... personally I think I might just use the original foreach version... maybe splitting out the GetDummy bit:

foreach (var item in itemlist)
{
    var dlist = item.examples.Select(ex => ex.GetDummy()).ToList();
    p.AddStuff(item.X,item.Y,dlist);
}
like image 50
Marc Gravell Avatar answered Feb 05 '26 13:02

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!