tags:

views:

69

answers:

1

Let me explain using this code sample:

var commands1 = new List<int> { 1 };
var lessons = new List<lesson>
{
   new lesson
   {
      hours = new List<hour>
      {
         new hour { period = 1 }
      }
   }
};
List<command> commands2
{
   get
   {
      return (
         from o in commands1
         select new command
         {
            hour = ????;
         }
      ).ToList();
   }
}

and in place of the ????. I need to get the hour object of which period corresponds to o. Normally I would loop through lessons, then loop through hours to check hour.period but I don't know how to do that in a LINQ query.

I hope that is clear enough (and that I paraphrased the code correctly).

+2  A: 
hour = lessons.SelectMany(l => l.hours).Where(h => h.period == o);
mquander
Perhaps `Single` instead of `Where`?
dtb
Note this doesn't provide the specific object, but rather an `IEnumerable<X>` of objects that meet the given criteria. If exactly one object is expected, use `.Single()`. If multiple can exist and you only want one, use `.First()`. If there's the possiblity that none exist and that's OK, use either `SingleOrDefault()` (for 0 to 1) or `FirstOrDefault()` (for 0 to many possibilities).
Anthony Pegram
Thanks all of you! I used your suggestion but with Single() and now it works. There should always be one object, and if not I'll throw an error.
Edootjuh