tags:

views:

1266

answers:

3

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
+6  A: 

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);
}
Marc Gravell
Learning when to not use LINQ is probably just as important as knowing when to use it :-)
Nifle
The funny thing is that I've have downvotes before for pointing out when something isn't a good fit for LINQ... odd.
Marc Gravell
You can't win, Marc.
plinth
+2  A: 

if itemlist is a List<T> collection you could do:

var p = new pmaker();
itemlist.ForEach(item => 
  p.AddStuff(item.X, item.Y, 
      (from ex in item.examples
       select ex.GetDummy()).ToList())
);

but if it's clearer this way? I think not, you should not use LINQ and delegates just because you like to, but because it states the intent of your code better.

Davy Landman
+1  A: 

Extending Marc's answer you could use All to add the items to p, but it's abusing All a bit unless p.AddStuff could fail.

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

If p.AddStuff can fail and you wanted to be sure all the items were added it would be completely appropriate to do it like this:

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