Linq filtering children's collection

I read a bunch of different topics, but I did not find what I was looking for.

I have an EF request:

var query = this.ObjectContext.Questions
            .Include("AnswerKey").Include("QuestionTypes")
            .Where(o => o.SurveyQuestions.Any(o2 => o2.SurveyID == id));

This worked fine until I realized that I was not taking my Active Flag into account for the AnswerKey child collection. In other words, this query should load all questions that have a parent poll of 3 (what it does), but download only those answers that have the true flag active.

I tried this:

var query = this.ObjectContext.AnswerKey
                .Include("Questions.QuestionTypes")
                .Where(ak =>
                    ak.Active == true &&
                    ak.Questions.SurveyQuestions.Any(sq => sq.SurveyID == 3) &&
                    ak.Questions.Active == true)
                    .AsEnumerable()
                    .Select(ak => ak.Questions).AsQueryable();

But it returns 1 question for each answer. So if a question has 4 answers, it appears 4 times ...

How can i do this?

+3
source share
2 answers

You can simply use Distinct()at the end to filter out duplicates:

  .AsEnumerable()
  .Select(ak => ak.Questions)
  .Distinct()
  .AsQueryable();
+2
source

Brokenglass . , .

SO... , , , .

+1

All Articles