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
  • I translated your Dutch identifiers to English using Google Translate. I hope I got it right. Commented Sep 16, 2010 at 20:08
  • Thanks. I simplified the code quite a bit, I'm actually getting both lessons and commands1 from XML. Commented Sep 16, 2010 at 20:36

1 Answer 1

3
hour = lessons.SelectMany(l => l.hours).Where(h => h.period == o);
Sign up to request clarification or add additional context in comments.

3 Comments

Perhaps Single instead of Where?
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).
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.