linq question: querying nested collections

前端 未结 4 352
囚心锁ツ
囚心锁ツ 2020-12-04 14:24

I have a Question class that has public List property that can contain several Answers.

I have a question repository which is respo

相关标签:
4条回答
  • 2020-12-04 14:42

    To find an answer.

    questions.SelectMany(q => q.Answers).Where(a => a.Name == "SomeName")
    

    To find the question of an answer.

    questions.Where(q => q.Answers.Any(a => a.Name == "SomeName"))
    

    In fact you will get collections of answers or questions and you will have to use First(), FirstOrDefault(), Single(), or SingleOrDefault() depending on your needs to get one specific answer or question.

    0 讨论(0)
  • 2020-12-04 14:45

    It seems you could use something like this:

    var query = from q in questions
                from a in q.Answers
                where a.Name == "Answer Name"
                select a;
    
    0 讨论(0)
  • 2020-12-04 14:49
    from question in Questions
    from answer in question.Answers
    where answer.Name == something
    select question // or select answer
    
    0 讨论(0)
  • 2020-12-04 15:03

    Use the SelectMany and First/FirstOrDefault (if you are needing one value)

    List<Questions> questions = //initialization;
    var someAnswer = questions.SelectMany(q=>q.Answers)
                              .First(a=>a.Name =="MyName");
    
    0 讨论(0)
提交回复
热议问题