Select everything that is at the 3rd depth level using Linq RRS feed

  • Question

  • Hi,

    The subject must not be sufficient to understand the problem. Here is the scenario,

    An object called QuestionCollection is given to you, QuestionCollection has a reference of Question[] called Questions, each Question has a reference of ParentQuestion[] called Parent Questions.

    All I am trying to do is to write a query to return all ParentQuestions

    Here is what I am trying to do


    var query = from c in QuestionCollection
                where c.Questions.Any(q => q.ParentQuestions.Count() > 0)
                select c.Questions.ParentQuestions;

    All it returns is Collection of ParentQuestion[] instead of collection of ParentQuestion.

    How do I fix that ?



    Tuesday, February 21, 2012 8:09 PM


  • You can use SelectMany to do this:

    var parentQuestions = QuestionCollection.SelectMany(qc => qc.Questions).SelectMany(q => q.ParentQuestions);

    Reed Copsey, Jr. -
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by Fahad349 Tuesday, February 21, 2012 8:42 PM
    Tuesday, February 21, 2012 8:22 PM