0

I have Questions table and List of CategoryIds. I have to get one question from each CategoryId randomly. Right now I'm doing like this:

var randomQuestions = new List<Question>();
foreach(int id in categoryIds){

randomQuestions.add(questions.Where(o => o.CategoryId== id).OrderBy(o => Guid.NewGuid()).FirstOrDefault());
}

But is there way to do it only with Linq? Thanks

alynurly
  • 1,669
  • 1
  • 15
  • 15

1 Answers1

3

This should do what you want in one query

var randomQuestions = questions
    .Where(q => categoryIds.Contains(q.CategoryId))
    .GroupBy(q = > q.CategoryId)
    .Select(grp => grp.OrderBy(_ => Guid.NewGuid()).First())
    .ToList();

That will first filter only questions in the categories you care about, then it groups on the category id and for each group it randomly picks one.

juharr
  • 31,741
  • 4
  • 58
  • 93